springboot异步方法

开启异步方法

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:
# 线程池最大数,默认Integer.MAX_VALUE
max-size: 16
# 核心线程数,默认8
core-size: 8
# 线程池队列容量,默认Integer.MAX_VALUE
queue-capacity: 100
# 线程空闲等待时间,默认60s
keep-alive: 60s

测试

  1. 异步方法
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    @Service
    public class TestService {

    //@Async表示方法是一个异步方法
    @Async
    public void async() {
    try {
    Thread.sleep(3000L);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    // 输出当前线程名称
    System.out.println(Thread.currentThread().getName());
    }
    }
  2. 测试
    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秒后,控制台打印线程名称