Java多线程导出,单线程压缩
1.客户端网页下载文件, 如果文件比较大,后台要进行压缩在传输给客户端。
2.后台进行压缩以后,要保存到服务器硬盘上, 当下次请求下载,则直接传输。
3.当请求下载的压缩文件不存在,需要查询数据,生成csv,最后将多个文件进行压缩保存到服务器硬盘上。
4.多线程进行查询,单线程进行压缩。
先看一个方法:
public String accountingVerificationExport(String zipFileName) {String zipSrc = "";try {/*** 导出到本地, 然后压缩成zip,并返回zip文件地址*/zipSrc = exportToLocation(zipFileName);} catch(Exception ex) {LOGGER.info("exec accountingVerificationExport error.{}", ex.getMessage());}return zipSrc;}
方法的参数zipFileName是指定压缩之后文件名.exportLocation
/*** 启动四个线程,同步导出* @param zipFileName* @return*/private String exportToLocation(String zipFileName) {ResourceLoadUtil rlu = new ResourceLoadUtil("/hx.properties");final Properties prop = rlu.getProp();final String exportLocation = prop.getProperty("hx.export.location.href");final CountDownLatch end = new CountDownLatch(4); //子线程final String [] typeName = new String[]{"receipt","output1","output2","back"};final List<String> fileSrcs = new ArrayList<String>();// 用于存放生成的文件名称final SessionFactory sessionFactory = accountingVerificationDao.getSessionFactory();LOGGER.info("导出线程开始运行 !");for(int i = 0; i < typeName.length; i++) {final int index = i;new Thread(new Runnable() {public void run() {LOGGER.info("启动子线程{}", typeName[index]);/*** 子线程等待*/boolean participate = ConcurrentUtil.bindHibernateSessionToThread(accountingVerificationDao.getSessionFactory());String fileSrc1 = exportList(exportLocation,prop.getProperty("hx.export."+typeName[index]+".fileName"),prop.getProperty("hx.export."+typeName[index]+".sheetColumn"),prop.getProperty("hx.export."+typeName[index]+".sql"));if(!StringUtil.isEmpty(fileSrc1)) {fileSrcs.add(fileSrc1);}ConcurrentUtil.closeHibernateSessionFromThread(participate, sessionFactory); end.countDown();LOGGER.info("{} 线程结束运行.",typeName[index]);}}).start();}try {end.await();} catch (InterruptedException e) {LOGGER.info("{}",e.getMessage());}LOGGER.info("导出线程结束运行 !");String zipSrcName = "";if(!CollectionUtil.isEmpty(fileSrcs) && fileSrcs.size() > 0) {zipSrcName = exportLocation + "/" + zipFileName + ".zip";File zip = new File(zipSrcName);// 压缩文件File srcfile[] = new File[fileSrcs.size()]; for (int i = 0, n = fileSrcs.size(); i < n; i++) { srcfile[i] = new File(fileSrcs.get(i)); } FileZip.ZipFiles(srcfile, zip); }return zipSrcName;}
CountDownLatch和SessionFactory/ConcurrentUtil.bindHibernateSessionToThread
CountDownLatch: 作用是启动多个线程,主线程等待所有线程完成在执行
ConcurrentUtil.bindHibernateSessionToThread: 最多线程情况下为每个线程绑定session(只有绑定了session才可以用spring的dao bean)
/*** 导出csv文件,csv没有文件行数限制* @param exportLocation 输出到硬盘的临时地址* @param fileName 文件名* @param titles 标题* @param sql* @return*/private String exportList(String exportLocation, String fileName, String titles, String sql) {String fileSrc = exportLocation + "/" + fileName + ".csv";List<Object> list = accountingVerificationDao.queryList(sql);//查询到货接收FileOutputStream out=null;OutputStreamWriter osw=null;BufferedWriter bw=null;boolean isSucess=false;try {out = new FileOutputStream(new File(fileSrc));osw = new OutputStreamWriter(out);bw =new BufferedWriter(osw);bw.append(titles).append("\r");//标题if(!CollectionUtil.isEmpty(list) && list.size() > 0) {for(Object obj : list){String data = (String) obj;if(!StringUtil.isEmpty(data)) {data = data.replaceAll("[\\n\\r\"]", "");data = data.replaceAll("[,]", ",");data = data.replace("@#$%&", ",").trim();bw.append(data).append("\r");}}isSucess=true;}} catch (Exception e) {isSucess=false;}finally{if(bw!=null){try {bw.close();bw=null;} catch (IOException e) {e.printStackTrace();} }if(osw!=null){try {osw.close();osw=null;} catch (IOException e) {e.printStackTrace();} }if(out!=null){try {out.close();out=null;} catch (IOException e) {e.printStackTrace();} }}if(isSucess) {return fileSrc;}return null;}
import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;/*** HIbernate子线程中绑定session* @author Administrator**/
public class ConcurrentUtil {public static boolean bindHibernateSessionToThread(SessionFactory sessionFactory) { if (TransactionSynchronizationManager.hasResource(sessionFactory)) { // Do not modify the Session: just set the participate flag. return true; } else { Session session = sessionFactory.openSession(); session.setFlushMode(FlushMode.MANUAL); SessionHolder sessionHolder = new SessionHolder(session); TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder); } return false; } public static void closeHibernateSessionFromThread(boolean participate, Object sessionFactory) { if (!participate) { SessionHolder sessionHolder = (SessionHolder)TransactionSynchronizationManager.unbindResource(sessionFactory); SessionFactoryUtils.closeSession(sessionHolder.getSession()); } }
}
Java多线程导出,单线程压缩相关推荐
- Java批量导出word压缩后的zip文件
一.js代码,由于参数比较大所以利用form表单使用post导出 function export_word(){var selectedRows = $("#dg").datagr ...
- 厉害了!java多线程导出excel
一.前言 红黑树,是一种高效的自平衡二叉查找树 Rudolf Bayer 于1978年发明红黑树,在当时被称为对称二叉 B 树(symmetric binary B-trees).后来,在1978年被 ...
- java导出excel压缩包_java动态导出excel压缩成zip下载的方法
本文实例为大家分享了java动态导出excel压缩成zip下载的具体代码,供大家参考,具体内容如下 package pack.java.io.demo; import java.io.Buffered ...
- java 中导出word后压缩文件_Java批量导出word压缩后的zip文件案例
一.js代码,由于参数比较大所以利用form表单使用post导出 function export_word(){ var selectedRows = $("#dg").datag ...
- JAVA单线程以及java多线程的实现方式
1.java单线程的实现 public class SingletonThread {@SuppressWarnings("static-access")public static ...
- java图片的导出,并压缩
java图片的导出,并压缩 java 压缩包jar包使用的是commons-compress-1.6.jar /*** 导出图片* @param request* @param response*/@ ...
- 【java多线程】多线程为什么跑的比单线程还要慢?!
问:多线程是不是能加快处理速度? 解析: 在使用多线程时,一定要知道一个道理:处理速度的最终决定因素是CPU.内存等,在单CPU(无论多少核)上,分配CPU资源的单位是"进程"而不 ...
- Java ZIP压缩 ZipArchiveEntry实现ZIP高效、Java多线程压缩、可控CPU使用率 Apache commons-compress
基于Apache开源commons-compress实现可控多线程压缩 目的 Java自带ZipEntity压缩方式太慢,严重影响压缩效率. commons-compress实现的ZipArchive ...
- Java excel导出压缩zip并加密(拿起即用,有用请点赞,不做白嫖怪!)
文章目录 1.前言 2.开发思路 以下某些类缺少的可以去我上篇文章拿 4.效果 5.结尾了 6.最最后 1.前言 上篇文章我有写了java用poi导出excel加密,但excel加密懂点电脑的都知道怎 ...
最新文章
- 中值定理符号怎么读_微分、微分中值定理、泰勒公式
- 全栈 - 20 Web 基础 网页的血肉 CSS
- 聊聊flink的CheckpointScheduler
- Spring源码解析-三级缓存与循环依赖,nginx架构图
- jQuery1.6以上attr改用prop
- 怎样制作html插件,自己动手制作一个Chrome插件 入门级
- 【spring boot】启动类启动 错误: 找不到或无法加载主类 com.codingapi.tm.TxManagerApplication 的解决方案
- 【渝粤题库】国家开放大学2021春1356高级英语听说(2)题目
- python ssl_Python3 ssl模块不可用的问题
- 在单页应用Vue中设置标题(title)
- strlen函数实现
- java cache组件_组件之Cache篇
- 第 3 章 UML 类图
- os.environ 和 keras.json
- 【水题】完美数(打表)
- 【故障诊断分析】基于matlab GUI小波包能量可视化设计【含Matlab源码 1788期】
- Adam自适应矩估计
- 微信开发者工具调试公众号网页
- [CVPR2021]pi-GAN: Periodic Implicit Generative Adversarial Networks for 3D-Aware Image Synthesis
- npx create-nuxt-app myapp2 安装报错