springboot集成线程池

springboot集成线程池

  1. yml文件添加线程配置参数
#配置线程池(这里只是配置基础属性)
thread:
  coreSize: 10
  maxSize: 200
  keepAliveTime: 10
  1. 添加线程配置类
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池配置类
 */
@Configuration
public class MyThreadConfig {

    @Value("${thread.coreSize}")
    private Integer coreSize;
    //最大连接数
    @Value("${thread.maxSize}")
    private Integer maxSize;
    //单位ns
    @Value("${thread.keepAliveTime}")
    private Integer keepAliveTime;
    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {
        return new ThreadPoolExecutor(
                coreSize,
                maxSize,
                keepAliveTime,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(100000),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );
    }
}

3 .声明引用

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private ThreadPoolExecutor executor;

	@Override
    public T save(T t) {

		代码段...
		//不带返回值异步操作
 		CompletableFuture.runAsync(() -> {
                setTimerTask(t);
            }, executor);
            
        代码段...
    }

	@SneakyThrows
    @Override
    public T getUser(Integer userId) {
		//带返回值异步操作
        CompletableFuture<T> completableFuture = CompletableFuture.supplyAsync(() -> {
          		代码段...
            return T;
        }, executor);

        return completableFuture.get();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值