1:在Spring Boot中,可以使用线程池来实现请求之间的隔离,避免互相影响和堵塞。具体步骤如下:
创建一个线程池,例如使用ThreadPoolTaskExecutor类:
@Configuration
public class AsyncConfig {
@Bean("asyncExecutor")
public Executor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10); // 设置核心线程数
executor.setMaxPoolSize(20); // 设置最大线程数
executor.setQueueCapacity(100); // 设置队列容量
executor.initialize();
return executor;
}
}
2:在需要异步执行的方法或者Controller中,使用@Async注解将方法标记为异步执行,同时指定使用上面创建的线程池:
@Service
public class MyService {
@Async("asyncExecutor")
public void asyncMethod() {
// 异步执行的代码逻辑
}
}
@RestController
public class MyController {
@Autowired
private MyService myService;
@GetMapping("/example")
public String example() {
myService.asyncMethod(); // 调用异步执行的方法
return "success";
}
}
以上示例使用了@Async注解将MyService中的asyncMethod()方法标记为异步执行,同时指定使用asyncExecutor线程池;在Controller中调用该方法时,由于异步执行,不会影响其他请求的执行。