一、异步多线程配置
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.Executor;
@EnableAsync
@Configuration
public class AsyncConfig {
@Bean(name = "threadPoolTaskExecutor")
public Executor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10); // 核心线程数
executor.setMaxPoolSize(20); // 最大线程数
executor.setQueueCapacity(500); // 队列大小
executor.setKeepAliveSeconds(60); // 线程空闲时的存活时间
executor.setThreadNamePrefix("MyThread-"); // 线程名称的前缀
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 拒绝策略
executor.initialize(); // 初始化
return executor;
}
}这段代码定义了一个配置类AsyncConfig,使用@EnableAsync注解开启Spring的异步任务支持,并定义了一个名为threadPoolTaskExecutor的线程池任务执行器。可以通过设置不同的参数来调整线程池的性能,确保应用在高并发情况下的稳定性。
二、使用
spring Boot多线程的使用
在Spring Boot中使用多线程,可以通过以下两种常见方式实现:
使用@Async注解:
在Spring Boot中,可以通过@Async注解来创建异步方法,Spring会将这些方法在后台的一个线程池中执行。
示例代码:
@Service
public class AsyncService {
@Async
public void executeAsyncTask() {
System.out.println("执行异步任务:" + Thread.currentThread().getName());
}
}
@RestController
public class AsyncController {
@Autowired
private AsyncService asyncService;
@GetMapping("/async")
public String asyncCall() {
asyncService.executeAsyncTask();
return "Async task started";
}
}自定义线程池:
通过配置自定义的ThreadPoolTaskExecutor,可以更细致地控制线程的使用。
示例代码:
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
@Override
@Bean
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(25);
executor.initialize();
return executor;
}
}
@Service
public class AsyncServiceWithThreadPool {
@Autowired
private AsyncTaskExecutor taskExecutor;
public void executeAsyncTask() {
taskExecutor.execute(() -> {
System.out.println("执行异步任务:" + Thread.currentThread().getName());
});
}
}在这两种方式中,@Async注解允许你在Spring管理的Bean中的方法上使用,而自定义线程池则允许你更细致地控制线程的行为。