jjzjj

多线程导出word

HeavenTang 2023-03-28 原文

导出word,以下为导出单个和zip的两种格式。

CountDownLatch运用
CountDownLatch和ExecutorService 线程池cachedThreadPool.submit

1、CountDownLatch 概念

CountDownLatch可以使一个获多个线程等待其他线程各自执行完毕后再执行。

CountDownLatch 定义了一个计数器,和一个阻塞队列, 当计数器的值递减为0之前,阻塞队列里面的线程处于挂起状态,当计数器递减到0时会唤醒阻塞队列所有线程,这里的计数器是一个标志,可以表示一个任务一个线程,也可以表示一个倒计时器,
CountDownLatch可以解决那些一个或者多个线程在执行之前必须依赖于某些必要的前提业务先执行的场景。

点击查看代码

    @Override
    public void batchExportWord(PreDefenceApplyDto preDefenceApplyDto) {
        SystemUserInfo loginUser = AuthorityUtil.getLoginUser();
        if (loginUser == null || StringUtils.isBlank(loginUser.getUserId())) {
            throw new ServiceException(SimpleErrorCode.UserNotLogin);
        }
        if(StringUtils.isBlank(preDefenceApplyDto.getGrade())){
            throw new ServiceException(301,"请选择年级");
        }
        String grade = preDefenceApplyDto.getGrade();
        List<String> collegeIds = preDefenceApplyDto.getCollegeIds();
        String majorId = preDefenceApplyDto.getMajorId();

        // 查询学生论文结果
        List<String> studentIds = preDefenceApplyMapper.selectHasResStu(grade,collegeIds,majorId);
        if(CollectionUtils.isEmpty(studentIds)){
            throw new ServiceException(302,"暂无审核通过的学生可导出");
        }
        //学校名称
        String schoolName = publicMapper.querySchoolName();

        FileOutputStream fileOutputStream = null;
        FileInputStream fileInputStream = null;
        BufferedInputStream bufferedInputStream = null;

        String downloadName = "情况表.zip";
        response.setContentType("application/zip;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + Encodes.urlEncode(downloadName));
        String realPath = request.getSession().getServletContext().getRealPath("");

        try (
                OutputStream outputStream = response.getOutputStream();
                // 压缩流
                ZipOutputStream zos = new ZipOutputStream(outputStream)){

                ExecutorService cachedThreadPool = Executors.newFixedThreadPool(studentIds.size());
                CountDownLatch latch = new CountDownLatch(studentIds.size());
                for(String stuId : studentIds){
                    cachedThreadPool.submit(() -> {
                        try {
                            zipPreWord(  bufferedInputStream, zos,
                                    stuId, schoolName ,realPath);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        latch.countDown();
                    });
                }
                cachedThreadPool.shutdown();
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedInputStream != null) {
                    bufferedInputStream.close();
                }
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public void zipPreWord( BufferedInputStream bufferedInputStream,ZipOutputStream zos,
                           String studentId,String schoolName ,String realPath) throws IOException {


        byte[] buffer = new byte[1024];
        int len = 0;

        PreDefenceApplyVo preDefenceApplyVo = preDefenceApplyMapper.resultQuery(studentId);
        String fileName =studentId+preDefenceApplyVo.getStudentName();
        fileName=fileName.replaceAll("/", "-")+"情况表.doc";
        String filePath = realPath + File.separator + fileName;

        File outFile = new File(filePath );

        Configuration configuration = new Configuration(Configuration.getVersion());
        configuration.setDefaultEncoding("UTF-8");
        configuration.setClassForTemplateLoading(this.getClass(), "/templates");

        Template template = null;
        try {
            template = configuration.getTemplate(schoolName + "情况表2.ftl"); 
        } catch (IOException e) {
            log.error("context", e);
            throw new ServiceException(SimpleErrorCode.ExecFailure);
        }

        Map<String, Object> params = new HashMap<>();
        params.put("preDefenceApplyVo", preDefenceApplyVo);
        params.put("schoolName", schoolName);
        try {
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));

            template.process(params, out);
        } catch (TemplateException e) {
            e.printStackTrace();
        }


        ZipEntry zipEntry = new ZipEntry(fileName);
        bufferedInputStream = new BufferedInputStream( new FileInputStream(outFile));
        zos.putNextEntry(zipEntry);
        while ((len = bufferedInputStream.read(buffer)) != -1) {
            zos.write(buffer, 0, len);
        }

    }
    @Override
    public void exportWord(PreDefenceApplyDto preDefenceApplyDto) {
        SystemUserInfo loginUser = AuthorityUtil.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException(SimpleErrorCode.UserNotLogin);
        }
        String studentId = loginUser.getUserId();
        if (preDefenceApplyDto != null && StringUtils.isNotBlank(preDefenceApplyDto.getStudentId())) {
            studentId = preDefenceApplyDto.getStudentId();
        }
        //学校名称
        String schoolName = publicMapper.querySchoolName();

        PreDefenceApplyVo preDefenceApplyVo = preDefenceApplyMapper.resultQuery(studentId);

        String fileName = schoolName + "情况表.doc";
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + stringToUnicode(fileName));

        String filePath = request.getSession().getServletContext().getRealPath("/");


        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Configuration configuration = new Configuration(Configuration.getVersion());
        configuration.setDefaultEncoding("UTF-8");
        configuration.setClassForTemplateLoading(this.getClass(), "/templates");

        Template template = null;
        try {
            template = configuration.getTemplate(schoolName + "情况表2.ftl"); 
        } catch (IOException e) {
            log.error("context", e);
            throw new ServiceException(SimpleErrorCode.ExecFailure);
        }

        Map<String, Object> params = new HashMap<>();
        params.put("preDefenceApplyVo", preDefenceApplyVo);
        params.put("schoolName", schoolName);

        File outFile = new File(filePath + "/" + fileName);
        byte[] buffer = new byte[1024];
        int len = 0;
        BufferedInputStream bufferedInputStream = null;
        try {

            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));

            try {
                template.process(params, out);
            } catch (TemplateException e) {
                e.printStackTrace();
            }
            FileInputStream fileInputStream = new FileInputStream(outFile);
            bufferedInputStream = new BufferedInputStream(fileInputStream);
            while ((len = bufferedInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }

            out.close();
            fileInputStream.close();
            bufferedInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (outFile.exists()) {
                if (!outFile.delete()) {
                    log.info("删除失败!");
                }
            }
        }

    }

有关多线程导出word的更多相关文章

  1. ruby-on-rails - Rails 3 I18 : translation missing: da. datetime.distance_in_words.about_x_hours - 2

    我看到这个错误:translationmissing:da.datetime.distance_in_words.about_x_hours我的语言环境文件:http://pastie.org/2944890我的看法:我已将其添加到我的application.rb中:config.i18n.load_path+=Dir[Rails.root.join('my','locales','*.{rb,yml}').to_s]config.i18n.default_locale=:da如果我删除I18配置,帮助程序会处理英语。更新:我在config/enviorments/devolpment

  2. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  3. ruby - 如何让Ruby捕获线程中的语法错误 - 2

    我正在尝试使用ruby​​编写一个双线程客户端,一个线程从套接字读取数据并将其打印出来,另一个线程读取本地数据并将其发送到远程服务器。我发现的问题是Ruby似乎无法捕获线程内的错误,这是一个示例:#!/usr/bin/rubyThread.new{loop{$stdout.puts"hi"abc.putsefsleep1}}loop{sleep1}显然,如果我在线程外键入abc.putsef,代码将永远不会运行,因为Ruby将报告“undefinedvariableabc”。但是,如果它在一个线程内,则没有错误报告。我的问题是,如何让Ruby捕获这样的错误?或者至少,报告线程中的错误?

  4. ruby - 如何在 ruby​​ 中运行后台线程? - 2

    我是ruby​​的新手,我认为重新构建一个我用C#编写的简单聊天程序是个好主意。我正在使用Ruby2.0.0MRI(Matz的Ruby实现)。问题是我想在服务器运行时为简单的服务器命令提供I/O。这是从示例中获取的服务器。我添加了使用gets()获取输入的命令方法。我希望此方法在后台作为线程运行,但该线程正在阻塞另一个线程。require'socket'#Getsocketsfromstdlibserver=TCPServer.open(2000)#Sockettolistenonport2000defcommandsx=1whilex==1exitProgram=gets.chomp

  5. ruby - Rails 开发服务器、PDFKit 和多线程 - 2

    我有一个使用PDFKit呈现网页的pdf版本的Rails应用程序。我使用Thin作为开发服务器。问题是当我处于开发模式时。当我使用“bundleexecrailss”启动我的服务器并尝试呈现任何PDF时,整个过程会陷入僵局,因为当您呈现PDF时,会向服务器请求一些额外的资源,如图像和css,看起来只有一个线程.如何配置Rails开发服务器以运行多个工作线程?非常感谢。 最佳答案 我找到的最简单的解决方案是unicorn.geminstallunicorn创建一个unicorn.conf:worker_processes3然后使用它:

  6. ruby - Ruby 1.9.1 中的 native 线程,对我有什么好处? - 2

    所以,Ruby1.9.1现在是declaredstable.Rails应该与它一起工作,并且正在慢慢地将gem移植到它。它具有native线程和全局解释器锁(GIL)。自从GIL到位后,原生线程是否比1.9.1中的绿色线程有任何优势? 最佳答案 1.9中的线程是原生的,但它们被“放慢了速度”,一次只允许一个线程运行。这是因为如果线程真的并行运行,它会混淆现有代码。优点:IO现在在线程中是异步的。如果一个线程阻塞在IO上,那么另一个线程将继续执行直到IO完成。C扩展可以使用真正的线程。缺点:任何非线程安全的C扩展都可能存在使用Thre

  7. ruby - 使写入文件线程安全 - 2

    我在一个ruby​​文件中有一个函数可以像这样写入一个文件File.open("myfile",'a'){|f|f.puts("#{sometext}")}这个函数在不同的线程中被调用,使得像上面这样的文件写入不是线程安全的。有谁知道如何以最简单的方式使这个文件写入线程安全?更多信息:如果重要的话,我正在使用rspec框架。 最佳答案 您可以通过File#flock给锁File.open("myfile",'a'){|f|f.flock(File::LOCK_EX)f.puts("#{sometext}")}

  8. Ruby 线程与 Watir - 2

    我编写了几个类来控制我想如何处理多个网站,两者都使用类似的方法(即登录、刷新)。每个类都打开自己的WATIR浏览器实例。classSite1definitialize@ie=Watir::Browser.newenddeflogin@ie.goto"www.blah.com"endend无线程的main中的代码示例如下require'watir'require_relative'site1'agents=[]agents这工作正常,但在当前代理完成登录之前不会移动到下一个代理。我想合并多线程来处理这个问题,但似乎无法让它工作。require'watir'require_relative

  9. ruby - 在多个线程中引用类方法会导致自动加载循环依赖崩溃 - 2

    代码:threads=[]Thread.abort_on_exception=truebegin#throwexceptionsinthreadssowecanseethemthreadseputs"EXCEPTION:#{e.inspect}"puts"MESSAGE:#{e.message}"end崩溃:.rvm/gems/ruby-2.1.3@req/gems/activesupport-4.1.5/lib/active_support/dependencies.rb:478:inload_missing_constant':自动加载常量MyClass时检测到循环依赖稍加研究后,

  10. Ruby 多线程/多处理读物 - 2

    任何人都可以推荐任何详细介绍Ruby多线程/多处理的复杂性的好的多线程/处理书籍/网站吗?我尝试使用ruby​​线程,基本上在1.9vm上的无死锁代码中它在jruby中遇到了死锁。是的,我意识到差异很大(jruby没有GIL),但我想知道是否有用于ruby​​中多线程编程的策略或类集,我只需要继续阅读。旁注:从java到ruby​​必须定义是否需要重新输入锁,这有点奇怪。 最佳答案 如果你使用Ruby1.9,你可以试试Fiber,它是Ruby中线程的一大改进http://ruby-doc.org/core-1.9/classes/F

随机推荐