Spring boot控制器异步多线程实现

Spring boot控制器异步多线程实现项目结构 D JAVA RES idea libraries mvn wrapper src main java yeye devops annotation

大家好,欢迎来到IT知识分享网。

前言

Spring中用@Async注解标记的方法,称为异步方法,它会在调用方的当前线程之外的独立的线程中执行,其实就相当于我们自己new Thread(()-> System.out.println("hello world !"))这样在另一个线程中去执行相应的业务逻辑.

@Async注解使用条件:

  • @Async注解一般用在类的方法上,如果用在类上,那么这个类所有的方法都是异步执行的;
  • 所使用的@Async注解方法的类对象应该是Spring容器管理的bean对象;
  • 调用异步方法类上需要配置上注解@EnableAsync
作用在方法上

项目结构 如下:

D:\JAVA-RES ├─src │ ├─main │ │ ├─java │ │ │ └─yeye │ │ │ └─devops │ │ │ ├─annotation │ │ │ ├─config │ │ │ ├─control │ │ │ ├─model │ │ │ └─service │ │ └─resources │ │ ├─static │ │ └─templates │ └─test │ └─java │ └─yeye │ └─devops PS D:\> 
定义线程池
package yeye.devops.config; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.AsyncConfigurer; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.Executor; /* * 开启异步执行配置类 * */ @Configuration @EnableAsync public class AsyncConfig implements AsyncConfigurer { 
    @Override public Executor getAsyncExecutor(){ 
    ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); // 线程池维护线程的最少数量 taskExecutor.setCorePoolSize(5); // 线程池中维护线程的最大数量 taskExecutor.setMaxPoolSize(10); // 线程池维护线程所使用的缓冲队列 taskExecutor.setQueueCapacity(25); //执行初始化 taskExecutor.initialize(); return taskExecutor; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { 
    return null; } } 
异步执行
package yeye.devops.service; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; /* * 异步任务执行类 * */ @Service public class AsyncTaskService { 
    @Async public void executeAsyncTask() { 
    System.out.println("执行异步任务1--"); } @Async public void executeAsyncTaskPlus() { 
    System.out.println("执行异步任务2--" ); } } 
作用控制器
package yeye.devops.control; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import yeye.devops.service.AsyncTaskService; @RestController public class IndexController { 
    private static final Logger logger = LoggerFactory.getLogger(IndexController.class); @Autowired private AsyncTaskService asynctaskservice; @GetMapping("api") public String hello(){ 
    logger.info("start----"); //调用service层的任务 asynctaskservice.executeAsyncTask(); logger.info("end----"); return "ok"; } } 
作用在方法上
PS D:\java-res\aly> tree src 卷 Setup 的文件夹 PATH 列表 卷序列号为 72D6-3A59 D:\JAVA-RES\ALY\SRC ├─main │ ├─java │ │ └─yeyese │ │ └─aly │ │ └─controller │ └─resources │ ├─static │ └─templates └─test └─java └─yeyese └─aly ├─config └─controller PS D:\java-res\aly> 
编写配置类

ExecutorConfig.java

package yeyese.aly.config; import org.springframework.context.annotation.Bean; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; @Slf4j public class ExecutorConfig { 
    @Bean public Executor asyncUpdateDriverExecutor() { 
    log.info("start asyncUpdateDriverExecutor"); ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); //配置核心线程数 executor.setCorePoolSize(5); //配置最大线程数 executor.setMaxPoolSize(5); //配置队列大小 executor.setQueueCapacity(99999); //配置线程池中的线程的名称前缀 executor.setThreadNamePrefix("async-UpdateDriver-"); // rejection-policy:当pool已经达到max size的时候,如何处理新任务 // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); //执行初始化 executor.initialize(); return executor; } } 

控制器使用:

@RestController @Async("asyncUpdateDriverExecutor") public class IndexController { 
    @GetMapping("api") public String test(){ 
    return "Ok"; } } 

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/150712.html

(0)
上一篇 2025-03-17 16:26
下一篇 2025-03-17 16:45

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信