spring boot 处理多线程的解决方案
来源:互联网 发布:人工智能机器人网 编辑:程序博客网 时间:2024/06/05 21:16
spring boot 处理多线程的解决方案(不知道可不可行),如果有更好的方案请指教
思路:用户的请求采用callable 来处理用户的每个请求,每个请求都给予回应, 那么线程池的size 就要根据并发数量决定了, 暂定30个
加入msg 是为了校验请求的发出者和多线程返回的结果对应上(观察msg返回值是否是用户请求的原始值,如果不是就说明多线程出现了相互干扰)
http://localhost:8080/test?msg=google
http://localhost:8080/test?msg=搜狗
返回的结果必然要和“msg” 里面的值对应上,不然就是出错了
package com.example.controller;import java.util.ArrayList;import java.util.List;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import javax.servlet.http.HttpServletRequest;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class MultiController {@RequestMapping("/test")public List<String> test(@RequestParam("msg") String msg ,HttpServletRequest request){List<String> list = new ArrayList<>();int taskSize = 30;ExecutorService pool = Executors.newFixedThreadPool(taskSize);Callable<List<String>> call =createCallable(request , msg);try {Future<List<String>> future = pool.submit(call);if(!future.isDone()){Thread.sleep(2000);}if(future.isDone()){list.addAll(future.get());}pool.shutdown();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ExecutionException e) {// TODO Auto-generated catch blocke.printStackTrace();}return list;}private Callable<List<String>> createCallable(final HttpServletRequest request, final String msg) {Callable<List<String>> call = new Callable<List<String>>() {@Overridepublic List<String> call() throws Exception {List<String> list = new ArrayList<>();/*for(int i=0; i<100; i++){list.add(UUID.randomUUID().toString());}*/list.add("time :"+System.currentTimeMillis()+ " :request:"+ request.hashCode()+ " msg:"+ msg);System.out.println(list);return list;}};return call;}}
0 0
- spring boot 处理多线程的解决方案
- Spring事务内多线程处理-解决方案
- spring boot: Whitelabel Error Page的解决方案
- spring boot: Whitelabel Error Page的解决方案
- spring boot: Whitelabel Error Page的解决方案
- spring boot的定时器实现多线程
- Spring-Boot中如何使用多线程处理任务
- Spring Boot使用多线程
- spring boot 集成多线程
- Spring Boot Web应用的异常处理
- Spring boot 处理 error 的套路
- Spring Boot 统一异常处理的案例
- spring boot 异常处理
- spring boot 异常处理
- spring boot 异常处理
- spring boot 异常处理
- spring boot 错误处理
- Spring Boot 错误处理
- cte with as 用法
- Nginx 安装与配置
- Python针对特定服务定制的代理工具V2.0----------------(代码组织简介)
- pycharm 配置spark运行环境
- Python实现读取目录所有文件的文件名并保存到txt文件代码
- spring boot 处理多线程的解决方案
- Spring学习笔记(三十):关于org.slf4j.logger的日志打印log.info(string,object)
- 事务概念以及更新丢失的解决
- 二叉树的后序遍历
- Windows下安装Scikit-Learn
- AngularJS 依赖注入
- Hexo安装+github部署博客教程
- jzoj P2131【2017.4.21普及】数字游戏
- oracle 存储过程基础知识