@Async异步注解的使用

我们在工作开发中经常可以不需要同步的任务,会降低性能,这个时候可以使用mq,也可以使用@Async异步注解,我们需要一下配置:

1.在启动类加上@EnableAsync注解

@SpringCloudApplication
@EnableAsync
public class DabaimaoApplication
{
    /**
     * 开启openfeign负载均衡
     * */
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

    public static void main(String[] args)
    {
        SpringApplication.run(DabaimaoApplication.class, args);
    }

}

2.在Bean中配置一个线程池

@Configuration
@EnableAsync
public class AsyncConfig {

    @Bean("asyncExecutor")
    public TaskExecutor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5); // 线程池核心线程数
        executor.setMaxPoolSize(10); // 线程池最大线程数
        executor.setQueueCapacity(20); // 队列容量
        executor.setThreadNamePrefix("Async-"); // 线程名前缀
        executor.initialize(); // 初始化
        return executor;
    }

    // 其他配置(如果有)
}

3.在对应的方法中加上注解

@Service
public class MyService {

    @Async("asyncExecutor") // 指定使用哪个线程池
    public void asyncMethod() {
        // 异步执行的逻辑
    }
}

4.这样的话调用这个方法会默认从配置的线程池创建线程异步执行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大白猫~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值