(六)SpringBoot 异步调用

异步调用
  1. 开启异步调用支持   

           @EnableAsync 启动类使用注解开启异步调用

   2. 添加异步方法

 @Async
        public void sendSms(){
           System.out.println("@Async");
        
     }   

3.配置线程池


@Configuration
@EnableAsync
public class ExecutorConfig {

    @Bean
    public Executor asyncServiceExecutor() {
        LoggerUtil.logger().info("start asyncServiceExecutor");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(5);
        //配置最大线程数
        executor.setMaxPoolSize(5);
        //配置队列大小
        executor.setQueueCapacity(1000);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix("async-service-");

        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }
}

4.使用注解添加到线程池

@Async("asyncServiceExecutor")
 public void sendSms(){
        System.out.println("@Async");
        }   

注意事项:1.在@SpringBootApplication启动类 添加注解@EnableAsync
                  2.异步方法使用注解@Async ,返回值为void或者Future
                  3.切记一点 ,异步方法和调用方法一定要* 写在不同的类中 *,如果写在一个类中, 是没有效果的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值