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
原创粉丝点击