spring boot 自定义线程池

时间:2024-04-12 09:49:20

本人初学,不好的地方还请指正

1、先创建spring boot项目

2、创建异步线程类

@Configuration
@EnableAsync
public class ExecutorPool implements AsyncConfigurer{

    private Logger log = LoggerFactory.getLogger(ExecutorPool.class);
    
    @Autowired
    private ThreadPoolConfig threadPoolConfig;
    
    public Executor getAsyncExecutor(){
        System.out.println("进入线程池");
        ThreadPoolTaskExecutor task = new ThreadPoolTaskExecutor();
        task.setCorePoolSize(threadPoolConfig.getCorePoolSize());
        task.setMaxPoolSize(threadPoolConfig.getMaxPoolSize());
        task.setQueueCapacity(threadPoolConfig.getQueueCapacity());
        task.setKeepAliveSeconds(threadPoolConfig.getKeepAliveSeconds());
        task.setThreadNamePrefix(threadPoolConfig.getThreadNamePrefix());
        // 异常处理策略,当超出最大线程数时有主线程执行task,保证task不丢失
        task.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        task.initialize();
        System.out.println("线程池最大核心数:"+ task.getCorePoolSize() + ";最大线程数:"+task.getMaxPoolSize()+",线程队列数:"+threadPoolConfig.getQueueCapacity());
        return task;
    }
    // 异步中异常处理
    public AsyncUncaughtExceptionHandler getAsyncExceptionHandler(){
        return new AsyncUncaughtExceptionHandler(){
            @Override
            public void handleUncaughtException(Throwable arg0, Method arg1, Object... arg2) {
                System.out.println("============="+arg0.getMessage()+"===========" + arg0);
                System.out.println("=============method:"+arg1.getName());
            }
        };
    }
}

3、异步线程调用类

@Component
public class AsyncTask {

    @Async
    public void AsyncQueryUserName(int i){
        try {
            new Thread().sleep(1000);
            System.out.println("task id :"+i+",线程名称"+Thread.currentThread().getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

4、实现类

@Service
public class UserServiceImpl implements UserService {

    private Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private AsyncTask ssyncTask;
    
    @Override
    public String queryUserName() {
        for(int i=0;i<200;i++){
            ssyncTask.AsyncQueryUserName(i);
        }
        return "success";
    }

}

这样便实现了spring boot的异步调用,结果如下图

spring boot 自定义线程池