开启异步方法
1 2 3 4 5 6 7 8
| @EnableAsync @SpringBootApplication public class MyApplication {
public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
|
配置(非必须)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| spring: task: execution: thread-name-prefix: spring-async- pool: max-size: 16 core-size: 8 queue-capacity: 100 keep-alive: 60s
|
测试
- 异步方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| @Service public class TestService {
@Async public void async() { try { Thread.sleep(3000L); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()); } }
|
- 测试
1 2 3 4 5 6 7 8 9 10 11 12
| @RestController public class TestController {
@Autowired private TestService testService;
@GetMapping("hello") public String hello() { testService.async(); return "hello"; } }
|
curl http://localhost:8080/hello
不同于同步方法,请求后会立即返回hello,线程等待3秒后,控制台打印线程名称