写一个springboot asnyc的例子包括线程池配置
首先,需要在pom.xml中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-async</artifactId>
</dependency>
接下来,我们需要在启动类上添加@EnableAsync注解,开启异步支持:
@SpringBootApplication
@EnableAsync
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
然后,我们可以在Controller中定义一个异步方法:
@RestController
public class MyController {
@Autowired
private MyService myService;
@GetMapping("/async")
public String async() {
myService.doSomethingAsync();
return "Async method called";
}
}
在Service中,我们需要使用@Async注解标注异步方法,并配置一个线程池:
@Service
public class MyService {
@Async("taskExecutor")
public void doSomethingAsync() {
// 异步方法的具体实现
}
@Bean("taskExecutor")
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(50);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("MyExecutor-");
executor.initialize();
return executor;
}
}
在上面的代码中,我们定义了一个名为"taskExecutor"的线程池,包括核心线程池大小、最大线程池大小、队列容量、线程名称前缀等配置。
现在,我们就可以通过调用异步方法来体验Spring Boot异步支持的效果了。当我们调用异步方法时,它将在一个新的线程中执行,而不会阻塞主线程
原文地址: https://www.cveoy.top/t/topic/dygx 著作权归作者所有。请勿转载和采集!