1、使用@Async注解
@Service
public class AsyncService {
// 告诉Spring这是一个异步的方法
@Async
public void hello() {
try {
Thread.sleep(3000);
}catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理");
}
}
2、使用@EnableAsync注解开启异步任务
//开启异步注解功能
@EnableAsync
@SpringBootApplication
public class Spring01Application {
public static void main(String[] args) {
SpringApplication.run(Spring01Application.class, args);
}
}
3、编写Controller调用
@RestController
public class AsyncController {
@Autowired
private AsyncService asyncService;
@GetMapping("/hello")
public String hello() {
asyncService.hello();
return "OK";
}
}