Version: Next

异步任务

  • 写一个线程睡眠service
@Service
public class AsynService {
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理....");
}
}
  • 写一个基本Controller
@RestController
public class AsynController {
@Autowired
AsynService asynService;
@GetMapping("/hello")
public String hello() {
asynService.hello();
return "ok";
}
}

访问/hello路由,会发现页面白了三秒才返回一个ok

我们希望网站直接返回一个ok,然后背后忙着处理请求

  1. 只需要在方法上用Async注解告诉Spring这是一个异步方法
@Service
public class AsynService {
@Async
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理....");
}
}
  1. 在SpringBoot启动入口用@EnableAsync开启异步功能
@EnableAsync
@SpringBootApplication
public class Springboot08EmailApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot08EmailApplication.class, args);
}
}