springboot 配置多线程

场景:

需要将消息队列中的消息存入输入库,消息队列中的数据每秒更新一次,数据量较大,写入数据库的操作用多线程处理

线程池的配置

@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(10);// 最小线程数
        taskExecutor.setMaxPoolSize(50);// 最大线程数
        taskExecutor.setQueueCapacity(10);// 等待队列
        //如果执行数超过最大线程数,调用者的线程会执行该任务
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }
}

调用,适用方法标注为异步调用

    @Async
    public void save(ADSB adsb){
        log.info("Thread:"+Thread.currentThread().getId());
        adsbMapper.insert(adsb);
    }

猜你喜欢

转载自my.oschina.net/lfy2008/blog/1794666