Spring线程池使用之@EnableAsync、@Async
Spring线程池的使用
Spring整合了ThreadPoolExecutor类,并且提供了ThreadPoolTaskExecutor类。使用的思路就是先将线程池对象放入到IOC容器中,然后通过解析注解进行AOP调用
第一步创建线程次对象,并注入到容器里
package cn.zl.swagger2demo.config;
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.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Configuration
@EnableAsync
public class ThreadPoolConfig {
private static final int corePoolSize = 5;
private static final int maxPoolSize = 10;
private static final int keepAliveTime = 10;
private static final int ququePoolSize = 10;
private static final String threadNamePrefix = "Async-Service-";
// 使用jdk自带的线程池
@Bean("taskExecutor")
public ThreadPoolExecutor threadPoolExecutor() {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize,
maxPoolSize,
keepAliveTime,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(ququePoolSize),
new CustomThreadFactory());
return threadPoolExecutor;
}
// 使用spring提供的线程池
@Bean("taskSpringExecutor")
public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);
threadPoolTaskExecutor.setQueueCapacity(ququePoolSize);
threadPoolTaskExecutor.setThreadNamePrefix(threadNamePrefix);
threadPoolTaskExecutor.setKeepAliveSeconds(keepAliveTime);
return threadPoolTaskExecutor;
}
}
第二步编写代码使用线程池
package cn.zl.swagger2demo.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
/**
* @ClassName : testAsyncService
* @Description :
* @Author : zl
* @Date: 2021-08-02 20:14
*/
@Service
public class AsyncService {
private final Logger log = LoggerFactory.getLogger(AsyncService.class);
// 通过此注解,标记使用哪个线程池。
@Async("taskExecutor")
public void service1() throws InterruptedException {
log.info("--------start-service1------------");
Thread.sleep(5000); // 模拟耗时
log.info("--------end-service1------------");
}
// 通过此注解,表示使用哪个线程池。
@Async("taskSpringExecutor")
public void service2() throws InterruptedException {
log.info("--------start-service2------------");
Thread.sleep(2000); // 模拟耗时
log.info("--------end-service2------------");
}
}