当前位置:   article > 正文

Springboot 整合多线程示例(简单易懂)_springboot 多线程

springboot 多线程

在之前的示例里我们实现了读取路径下所有csv文件,将其中数据转化为json对象并另存为json文件的功能。但是,在之前的代码中,我们是以顺序处理的方式依次处理csv文件的,只有在一个文件处理完之后才能开始处理下一个文件,总处理时间为所有文件处理时间之和,当文件数据量较大时会花费很长时间;所以,在这里我们引入多线程处理方法,让多个文件同时进行处理,这样总处理时间会大大减少。 

Springboot读取.csv文件并转化为JSON对象

一. 多线程引入

1. 配置线程池

  1. package com.example.demo.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.scheduling.annotation.EnableAsync;
  5. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
  6. import java.util.concurrent.Executor;
  7. import java.util.concurrent.ThreadPoolExecutor;
  8. @Configuration
  9. @EnableAsync
  10. public class AsyncConfiguration {
  11. @Bean("async")
  12. public Executor doSomethingExecutor() {
  13. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  14. // 核心线程数:线程池创建时候初始化的线程数
  15. executor.setCorePoolSize(10);
  16. // 最大线程数:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
  17. executor.setMaxPoolSize(20);
  18. // 缓冲队列:用来缓冲执行任务的队列
  19. executor.setQueueCapacity(500);
  20. // 允许线程的空闲时间60秒:当超过了核心线程之外的线程在空闲时间到达之后会被销毁
  21. executor.setKeepAliveSeconds(60);
  22. // 线程池名的前缀:设置好了之后可以方便我们定位处理任务所在的线程池
  23. executor.setThreadNamePrefix("async-");
  24. // 缓冲队列满了之后的拒绝策略:由调用线程处理(一般是主线程)
  25. executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  26. executor.initialize();
  27. return executor;
  28. }
  29. }

2. 编写示例

在方法前加上注释 @Async("async") 声明此方法可使用多线程

  1. package com.example.demo.controller;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.example.demo.service.AsyncServer;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.web.bind.annotation.CrossOrigin;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RequestMethod;
  8. import org.springframework.web.bind.annotation.RestController;
  9. @RestController
  10. @RequestMapping("/async")
  11. @CrossOrigin(value = "*", maxAge = 3600)
  12. public class AsyncController {
  13. @Autowired
  14. private AsyncServer server;
  15. @RequestMapping(value = "/test", method = RequestMethod.GET)
  16. public JSONObject asyncTest() throws InterruptedException{
  17. JSONObject output = new JSONObject();
  18. long startTime = System.currentTimeMillis();
  19. int counter = 10;
  20. for (int i = 0; i<counter ; i++) {
  21. server.asyncTest(i);
  22. }
  23. long endTime = System.currentTimeMillis();
  24. output.put("msg", "succeed");
  25. output.put("花费时间: ", endTime-startTime);
  26. return output;
  27. }
  28. }
  1. package com.example.demo.service;
  2. import org.springframework.scheduling.annotation.Async;
  3. import org.springframework.stereotype.Service;
  4. @Service
  5. public class AsyncServer {
  6. @Async("async")
  7. public void asyncTest(Integer counter) throws InterruptedException{
  8. Thread.sleep(2000);
  9. System.out.println("线程" + Thread.currentThread().getName() + " 执行异步任务:" + counter);
  10. }
  11. }

以上示例为创建 10 个线程,每个线程阻塞 2 秒后打印出结果,使用 postman 调用接口结果如下:

 可以看到计数 counter 并不是按 1~9 顺序打出的,证明是多线程同步执行的;但是 postman 返回结果中花费时间为 5 ,而代码中设置了每个线程阻塞 2 秒后打印结果 ,所以这里主线程是非阻塞式的,也就是说主线程运行到 for 循环语句后并没有等待所有线程执行结束后再继续运行;所以这里我们要将他修改为阻塞式。

  1. package com.example.demo.controller;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.example.demo.service.AsyncServer;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.web.bind.annotation.CrossOrigin;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RequestMethod;
  8. import org.springframework.web.bind.annotation.RestController;
  9. import java.util.concurrent.CountDownLatch;
  10. @RestController
  11. @RequestMapping("/async")
  12. @CrossOrigin(value = "*", maxAge = 3600)
  13. public class AsyncController {
  14. @Autowired
  15. private AsyncServer server;
  16. @RequestMapping(value = "/test", method = RequestMethod.GET)
  17. public JSONObject asyncTest() throws InterruptedException{
  18. JSONObject output = new JSONObject();
  19. long startTime = System.currentTimeMillis();
  20. int counter = 10;
  21. CountDownLatch countDownLatch = new CountDownLatch(counter);
  22. for (int i = 0; i<counter ; i++) {
  23. server.asyncTest(i, countDownLatch);
  24. }
  25. countDownLatch.await();
  26. long endTime = System.currentTimeMillis();
  27. output.put("msg", "succeed");
  28. output.put("花费时间: ", endTime-startTime);
  29. return output;
  30. }
  31. }
  1. package com.example.demo.service;
  2. import org.springframework.scheduling.annotation.Async;
  3. import org.springframework.stereotype.Service;
  4. import java.util.concurrent.CountDownLatch;
  5. @Service
  6. public class AsyncServer {
  7. @Async("async")
  8. public void asyncTest(Integer counter, CountDownLatch countDownLatch) throws InterruptedException{
  9. Thread.sleep(2000);
  10. System.out.println("线程" + Thread.currentThread().getName() + " 执行异步任务:" + counter);
  11. countDownLatch.countDown();
  12. }
  13. }
  • countDownLatch这个类使一个线程等待其他线程各自执行完毕后再执行。
  • 是通过一个计数器来实现的,计数器的初始值是线程的数量。每当一个线程执行完毕后,计数器的值就-1,当计数器的值为0时,表示所有线程都执行完毕,然后在闭锁上等待的线程就可以恢复工作了。

 可以看到,现在是等待所有线程都运行结束之后,主线程才继续进行。

二. 实际使用示例

这里以上一篇文档中对csv文件的批处理方法为例:

Springboot读取.csv文件并转化为JSON对象

  1. package com.example.dataprocessing.controller;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.example.dataprocessing.service.ReadCSVServer;
  4. import org.json.JSONException;
  5. import org.springframework.web.bind.annotation.*;
  6. import javax.annotation.Resource;
  7. import java.io.IOException;
  8. import java.util.List;
  9. import java.util.concurrent.CountDownLatch;
  10. import java.util.concurrent.ExecutionException;
  11. @RestController
  12. @RequestMapping("/read")
  13. @CrossOrigin(value = "*", maxAge = 3600)
  14. public class ReadCSVController {
  15. @Resource
  16. private ReadCSVServer server;
  17. @RequestMapping(value = "/csv", method = RequestMethod.POST)
  18. public JSONObject readCSVFil(@RequestBody JSONObject get) throws IOException,JSONException,InterruptedException, ExecutionException {
  19. JSONObject output = new JSONObject();
  20. String filePath = get.getString("filePath");
  21. filePath.replace("\\", "/");
  22. long startTime = System.currentTimeMillis();
  23. List<String> filePaths = server.getFileInPath(filePath);
  24. CountDownLatch countDownLatch = new CountDownLatch(filePaths.size());
  25. if (filePaths != null) {
  26. for (String fileName : filePaths) {
  27. server.readCSVAndWrite(countDownLatch, fileName, filePath);
  28. }
  29. }
  30. countDownLatch.await();
  31. long endTime = System.currentTimeMillis();
  32. output.put("msg", "succeed");
  33. output.put("data", "已处理"+filePaths.size()+"个文件;耗时"+(endTime-startTime)/1000+"秒");
  34. return output;
  35. }
  36. }
  1. package com.example.dataprocessing.service;
  2. import com.alibaba.fastjson.JSON;
  3. import com.example.dataprocessing.dao.impl.ReadCSVImpl;
  4. import org.json.JSONException;
  5. import org.json.JSONObject;
  6. import org.springframework.beans.factory.annotation.Value;
  7. import org.springframework.data.mongodb.core.MongoTemplate;
  8. import org.springframework.scheduling.annotation.Async;
  9. import org.springframework.stereotype.Service;
  10. import javax.annotation.Resource;
  11. import java.io.*;
  12. import java.util.ArrayList;
  13. import java.util.List;
  14. import java.util.Scanner;
  15. import java.util.concurrent.CountDownLatch;
  16. @Service
  17. public class ReadCSVServer {
  18. /**
  19. * 读取路径下所有.csv文件
  20. * @return List<String>
  21. * */
  22. public List<String> getFileInPath(String filePath) {
  23. List<String> csvList = new ArrayList<>();
  24. File f = new File(filePath);
  25. File[] ts = f.listFiles();
  26. for (int i=0;i<ts.length;i++) {
  27. if (ts[i].isFile()) {
  28. String fileName = ts[i].toString();
  29. //获取最后一个.的位置
  30. int lastIndexOf = fileName.lastIndexOf(".");
  31. //获取文件的后缀名
  32. String suffix = fileName.substring(lastIndexOf);
  33. if (suffix.equals(".csv")) {
  34. csvList.add(fileName);
  35. }
  36. }
  37. }
  38. return csvList;
  39. }
  40. @Async("async")
  41. public void readCSVAndWrite(CountDownLatch countDownLatch, String fileName, String filePath) throws IOException,JSONException,InterruptedException {
  42. List<String[]> list = new ArrayList<>();
  43. FileInputStream inputStream = null;
  44. Scanner sc = null;
  45. try {
  46. inputStream = new FileInputStream(fileName);
  47. if (inputStream.getChannel().size() == 0) {
  48. countDownLatch.countDown();
  49. }
  50. sc = new Scanner(inputStream, "UTF-8");
  51. String headLine = new String();
  52. String[] headArray = null;
  53. if (sc.hasNextLine()) {
  54. headLine = sc.nextLine();
  55. headArray = headLine.split(",");
  56. }
  57. while (sc.hasNextLine()) {
  58. String line = sc.nextLine();
  59. String[] strArray = line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
  60. if (strArray.length!=0) {
  61. list.add(strArray);
  62. }
  63. if (list.size() == 30000) {
  64. List<com.alibaba.fastjson.JSONObject> jsons = csv2JSON(headArray, list);
  65. writeObj(jsons, filePath, fileName);
  66. list.clear();
  67. } else if (!sc.hasNextLine()) {
  68. List<com.alibaba.fastjson.JSONObject> jsons = csv2JSON(headArray, list);
  69. countDownLatch.countDown();
  70. writeObj(jsons, filePath, fileName);
  71. }
  72. }
  73. // note that Scanner suppresses exceptions
  74. if (sc.ioException() != null) {
  75. throw sc.ioException();
  76. }
  77. } finally {
  78. if (inputStream != null) {
  79. inputStream.close();
  80. }
  81. if (sc != null) {
  82. sc.close();
  83. }
  84. }
  85. }
  86. /**
  87. * 将csv中的一行数据转换成一个一级json
  88. * @param keys json的key,顺序需与csv中的value对应
  89. * @param values csv中数据作为value
  90. * @return
  91. */
  92. @Async("async")
  93. public JSONObject csv2JSON(String[] keys, String[] values) throws JSONException {
  94. JSONObject json = new JSONObject();
  95. for (int i = 0; i < keys.length; i++) {
  96. try{
  97. String value = values[i].replace("\"", "");
  98. json.put(keys[i],value);
  99. }
  100. catch (ArrayIndexOutOfBoundsException e){
  101. }
  102. }
  103. return json;
  104. }
  105. /**
  106. * 将csv的每一行数据都转换成一级json,返回json数组
  107. * @param keys json的key,顺序需与csv中的value对应
  108. * @param stringsList 读取csv返回的List<String[]>
  109. * @return
  110. */
  111. @Async("async")
  112. public List<com.alibaba.fastjson.JSONObject> csv2JSON(String[] keys, List<String[]> stringsList) throws JSONException {
  113. List<com.alibaba.fastjson.JSONObject> jsons = new ArrayList<>();
  114. int index = 0 ;
  115. for (String[] strings : stringsList
  116. ) {
  117. JSONObject json = this.csv2JSON(keys, strings);
  118. String jsonStr = json.toString();
  119. com.alibaba.fastjson.JSONObject obj = JSON.parseObject(jsonStr);
  120. jsons.add(obj);
  121. }
  122. return jsons;
  123. }
  124. @Async("async")
  125. public void writeObj(List<com.alibaba.fastjson.JSONObject> jsonObjects, String path, String fileName) throws IOException {
  126. String newFileName = fileName.replace(".csv", ".txt");
  127. try {
  128. // 防止文件建立或读取失败,用catch捕捉错误并打印,也可以throw
  129. /* 写入Txt文件 */
  130. File writename = new File(path);// 相对路径,如果没有则要建立一个新的output。txt文件
  131. if(!writename.exists()){
  132. writename.mkdirs();
  133. }
  134. writename = new File(newFileName);// 相对路径,如果没有则要建立一个新的output。txt文件
  135. writename.createNewFile(); // 创建新文件
  136. BufferedWriter out = new BufferedWriter(new FileWriter(writename, true));
  137. for (com.alibaba.fastjson.JSONObject jsonObject: jsonObjects) {
  138. out.write(jsonObject.toString()+"\n");
  139. }
  140. System.out.println("写入成功!");
  141. out.flush(); // 把缓存区内容压入文件
  142. out.close(); // 最后记得关闭文件
  143. } catch (Exception e) {
  144. e.printStackTrace();
  145. }
  146. }
  147. }

未使用多线程时:

 可以看到是一个文件一个文件依次进行处理的。

使用多线程时:

可以看到是5个文件同时进行处理的。

 耗时为处理最大的文件所花费的时间,可以看到,花费的时间大大减少;毫无疑问,当需要处理的文件数量更庞大时,耗费时间的缩减将会更加明显。

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号