springboot使用@Async异步线程池(简易)

gitee源码

实际项目中, 使用@Async调用线程池,推荐使用自定义线程池的模式,不推荐直接使用@Async直接实现异步,直接使用会不断的创建线程,最终会导致系统占用内存过高。

1、自定义线程池

复制代码

package com.sxsoft.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
* @program: sxsoft_operation_admin
* @ClassName TaskPoolConfig
* @description:
* 自定义线程池,线程池参数配置,多个线程池实现线程池隔离,@Async注解,默认使用系统自定义线程池,可在项目中设置多个线程池,
* 在异步调用的时候,指明需要调用的线程池名称,比如:@Async("taskName")
* @author: ht
* @create: 2023-07-18 14:00
* @Version 1.0
**/
@EnableAsync
@Configuration
public class TaskPoolConfig {

@Bean("taskExecutor")
public Executor taskExecutor() {
//返回可用处理器的Java虚拟机的数量 12
int i = Runtime.getRuntime().availableProcessors();
System.out.println("系统最大线程数 :" + i);
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心线程池大小
executor.setCorePoolSize(16);
//最大线程数
executor.setMaxPoolSize(20);
//配置队列容量,默认值为Integer.MAX_VALUE
executor.setQueueCapacity(99999);
//活跃时间
executor.setKeepAliveSeconds(60);
//线程名字前缀
executor.setThreadNamePrefix("asyncServiceExecutor-");
//设置此执行程序应该在关闭时阻止的最大秒数,以便在容器的其余部分继续关闭之前等待剩余的任务完成他们的执行
executor.setAwaitTerminationSeconds(60);
//等待所有的任务结束后再关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(true);
return executor;
}
}
 
复制代码

 2、service层使用

复制代码
public interface AsyncService {
 
    MessageResult sendSms(String callPrefix, String mobile, String actionType, String content);
 
    MessageResult sendEmail(String email, String subject, String content);
}
 
@Slf4j
@Service
public class AsyncServiceImpl implements AsyncService {
 
    @Autowired
    private IMessageHandler mesageHandler;
 
    @Override
    @Async("taskExecutor")
    public MessageResult sendSms(String callPrefix, String mobile, String actionType, String content) {
        try {
 
            Thread.sleep(1000);
            mesageHandler.sendSms(callPrefix, mobile, actionType, content);
 
        } catch (Exception e) {
            log.error("发送短信异常 -> ", e)
        }
    }
    
    @Override
    @Async("taskExecutor")
    public sendEmail(String email, String subject, String content) {
        try {
 
            Thread.sleep(1000);
            mesageHandler.sendsendEmail(email, subject, content);
 
        } catch (Exception e) {
            log.error("发送email异常 -> ", e)
        }
    }
}
复制代码

 

posted on   五官一体即忢  阅读(168)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示