Home >Java >javaTutorial >How to use multi-threading elegantly in SpringBoot
The @EnableAsync annotation needs to be added to the SpringBoot application to enable asynchronous calls. Generally, a thread pool will be configured, and the asynchronous method will be completed by a specific thread pool, as follows:
@Configuration @EnableAsync public class AsyncConfiguration { @Bean("doSomethingExecutor") public Executor doSomethingExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // 核心线程数:线程池创建时候初始化的线程数 executor.setCorePoolSize(10); // 最大线程数:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程 executor.setMaxPoolSize(20); // 缓冲队列:用来缓冲执行任务的队列 executor.setQueueCapacity(500); // 允许线程的空闲时间60秒:当超过了核心线程之外的线程在空闲时间到达之后会被销毁 executor.setKeepAliveSeconds(60); // 线程池名的前缀:设置好了之后可以方便我们定位处理任务所在的线程池 executor.setThreadNamePrefix("do-something-"); // 缓冲队列满了之后的拒绝策略:由调用线程处理(一般是主线程) executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy()); executor.initialize(); return executor; } }
The method of use is very simple, add @Async annotation to the method that needs asynchronous
@RestController public class AsyncController { @Autowired private AsyncService asyncService; @GetMapping("/open/something") public String something() { int count = 10; for (int i = 0; i < count; i++) { asyncService.doSomething("index = " + i); } return "success"; } } @Slf4j @Service public class AsyncService { // 指定使用beanname为doSomethingExecutor的线程池 @Async("doSomethingExecutor") public String doSomething(String message) { log.info("do something, message={}", message); try { Thread.sleep(1000); } catch (InterruptedException e) { log.error("do something error: ", e); } return message; } }
Access: 127.0.0.1:8080/open/something, the log is as follows
2023 -02-06 23:42:42.486 INFO 21168 --- [io-8200-exec-17] x.g.b.system.controller.AsyncController : do something end, time 8 milliseconds
2023-02-06 23:42:42.488 INFO 21168 --- [ do-something-1] x.gits.boot.system.service.AsyncService : do something, message=index = 0
2023-02-06 23:42:42.488 INFO 21168 --- [ do-something-5] x.gits.boot.system.service.AsyncService : do something, message=index = 4
2023-02-06 23:42:42.488 INFO 21168 --- [ do-something- 4] x.gits.boot.system.service.AsyncService : do something, message=index = 3
2023-02-06 23:42:42.488 INFO 21168 --- [ do-something-6] x.gits .boot.system.service.AsyncService : do something, message=index = 5
2023-02-06 23:42:42.488 INFO 21168 --- [ do-something-9] x.gits.boot.system. service.AsyncService : do something, message=index = 8
2023-02-06 23:42:42.488 INFO 21168 --- [ do-something-8] x.gits.boot.system.service.AsyncService : do something, message=index = 7
2023-02-06 23:42:42.488 INFO 21168 --- [do-something-10] x.gits.boot.system.service.AsyncService : do something, message=index = 9
2023-02-06 23:42:42.488 INFO 21168 --- [ do-something-7] x.gits.boot.system.service.AsyncService : do something, message=index = 6
2023-02-06 23:42:42.488 INFO 21168 --- [ do-something-2] x.gits.boot.system.service.AsyncService : do something, message=index = 1
2023-02-06 23:42:42.488 INFO 21168 --- [ do-something-3] x.gits.boot.system.service.AsyncService : do something, message=index = 2
It can be seen that it has The effect of asynchronous execution is achieved, and the thread pool we configured is used.
When the asynchronous method has a return value, how to get the return result of the asynchronous method execution? At this time, the method that needs to be called asynchronously has the return value CompletableFuture.
CompletableFuture is an enhancement to Feature. Feature can only handle simple asynchronous tasks, while CompletableFuture can perform complex combinations of multiple asynchronous tasks. As follows:
@RestController public class AsyncController { @Autowired private AsyncService asyncService; @SneakyThrows @ApiOperation("异步 有返回值") @GetMapping("/open/somethings") public String somethings() { CompletableFuture<String> createOrder = asyncService.doSomething1("create order"); CompletableFuture<String> reduceAccount = asyncService.doSomething2("reduce account"); CompletableFuture<String> saveLog = asyncService.doSomething3("save log"); // 等待所有任务都执行完 CompletableFuture.allOf(createOrder, reduceAccount, saveLog).join(); // 获取每个任务的返回结果 String result = createOrder.get() + reduceAccount.get() + saveLog.get(); return result; } } @Slf4j @Service public class AsyncService { @Async("doSomethingExecutor") public CompletableFuture<String> doSomething1(String message) throws InterruptedException { log.info("do something1: {}", message); Thread.sleep(1000); return CompletableFuture.completedFuture("do something1: " + message); } @Async("doSomethingExecutor") public CompletableFuture<String> doSomething2(String message) throws InterruptedException { log.info("do something2: {}", message); Thread.sleep(1000); return CompletableFuture.completedFuture("; do something2: " + message); } @Async("doSomethingExecutor") public CompletableFuture<String> doSomething3(String message) throws InterruptedException { log.info("do something3: {}", message); Thread.sleep(1000); return CompletableFuture.completedFuture("; do something3: " + message); } }
Access interface
C:\Users\Administrator>curl -X GET "http://localhost:8080/open/something" -H "accept: * /*"
do something1: create order;
do something2: reduce account;
do something3: save log
The key logs on the console are as follows:
2023-02-06 00:27:42.238 INFO 5672 --- [ do-something-3] x.gits.boot.system.service.AsyncService : do something3: save log
2023-02- 06 00:27:42.238 INFO 5672 --- [ do-something-2] x.gits.boot.system.service.AsyncService : do something2: reduce account
2023-02-06 00:27:42.238 INFO 5672 --- [ do-something-1] x.gits.boot.system.service.AsyncService : do something1: create order
@Async annotation will be as follows Several scenarios failed, which means that the @Async annotation was clearly used, but multi-threading was not used.
Asynchronous methods are modified with the static keyword;
The asynchronous class is not a bean of the Spring container (generally use the annotations @Component and @Service, and can be scanned by Spring);
The @EnableAsync annotation is not added to the SpringBoot application;
In the same class, a method call For another method with @Async annotation, the annotation will not take effect. The reason is that the method annotated with @Async is executed in the proxy class.
It should be noted that: The return value of an asynchronous method using the annotation @Async can only be void or Future and its subclasses. When the return result is other types, the method will still be executed asynchronously. , but the return values are all null. Part of the source code is as follows:
AsyncExecutionInterceptor#invoke
Through the above examples, @Async actually still passes Future or CompletableFuture For asynchronous execution, Spring has encapsulated it to make it more convenient for us to use.
The above is the detailed content of How to use multi-threading elegantly in SpringBoot. For more information, please follow other related articles on the PHP Chinese website!