springboot集成线程池
- yml文件添加线程配置参数
#配置线程池(这里只是配置基础属性)
thread:
coreSize: 10
maxSize: 200
keepAliveTime: 10
- 添加线程配置类
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();
}