SpringBoot2对接线程池
1、配置线程池Bean
package com.itennishy.test.config;
import java.util.concurrent.ThreadPoolExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
@EnableAsync
public class ThreadPoolTaskConfig {
private static final int corePoolSize = 20;
private static final int maxPoolSize = 100;
private static final int keepAliveTime = 10;
private static final int queueCapacity = 200;
private static final String threadNamePrefix = "Async-Service-";
@Bean("taskExecutor")
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setKeepAliveSeconds(keepAliveTime);
executor.setThreadNamePrefix(threadNamePrefix);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
}
2、配置Service测试接口
package com.itennishy.test.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class OrderTaskServic {
@Async
public void orderTask() throws InterruptedException {
log.info("发送短信方法---- 1 执行开始");
Thread.sleep(5000);
log.info("发送短信方法---- 1 执行结束");
}
}
3、编写测试的Controller
package com.itennishy.test.controller;
import com.itennishy.test.service.OrderTaskServic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@Autowired
private OrderTaskServic orderTaskServic;
@GetMapping("/test1")
@ResponseBody
public void test1() {
while (true){
try {
orderTaskServic.orderTask();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}