spring-boot多线程并发执行任务

提示:以下是本篇文章正文内容,下面案例可供参考


使用步骤

1.config文件

复制代码
package com.cooker.lottery_system.common.config;

import org.springframework.beans.factory.annotation.Value;
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.ThreadPoolExecutor;


@Configuration
@EnableAsync
public class ExecutorConfig {
    @Value("${async.executor.thread.core_pool_size}")
    private int corePoolSize;
    @Value("${async.executor.thread.max_pool_size}")
    private int maxPoolSize;
    @Value("${async.executor.thread.queue_capacity}")
    private int queueCapacity;
    @Value("${async.executor.thread.name.prefix}")
    private String namePrefix;


    @Bean(name = "asyncServiceExecutor")
    public ThreadPoolTaskExecutor asyncServiceExecutor(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new
                ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
        threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);
        threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
        threadPoolTaskExecutor.setKeepAliveSeconds(3);
        threadPoolTaskExecutor.setThreadNamePrefix(namePrefix);
        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执⾏任务,⽽是由调⽤者所在的线程来执⾏
        threadPoolTaskExecutor.setRejectedExecutionHandler(new
                ThreadPoolExecutor.AbortPolicy());
        //加载
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }
}

2、application.properties

复制代码
## 线程池 ##
async.executor.thread.core_pool_size=10
async.executor.thread.max_pool_size=20
async.executor.thread.queue_capacity=20
async.executor.thread.name.prefix=async-service-

3、对象注入

复制代码
@Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

4、并行执行

复制代码
// 短信通知
        threadPoolTaskExecutor.execute(()->sendMessage(winningRecordDOList));
        // 邮件通知
        threadPoolTaskExecutor.execute(()->sendMail(winningRecordDOList));
相关推荐
希望永不加班2 小时前
SpringBoot 配置 HTTPS(自签名证书+正式证书)
java·spring boot·后端·spring·https
dmlcq2 小时前
一文读懂 PageQueryUtil:分页查询的优雅打开方式
开发语言·windows·python
不会写DN2 小时前
JS 最常用的性能优化 防抖和节流
开发语言·javascript·ecmascript
HLC++2 小时前
数据结构--树
c语言·开发语言·数据结构
2501_945424802 小时前
C++构建缓存加速
开发语言·c++·算法
2401_851272992 小时前
多平台UI框架C++开发
开发语言·c++·算法
骇客野人2 小时前
Java实现B+树,体会B+树做索引的精妙
java·开发语言·b树
楼田莉子2 小时前
C++数据结构:基数树
开发语言·数据结构·c++·学习
m0_518019482 小时前
C++中的命令模式实战
开发语言·c++·算法