1、創建一個SpringBoot的Web項目
2、開啟異步注解功能
@EnableAsync
//開啟異步注解功能
@EnableAsync
@SpringBootApplication
public class Springboot12TaskApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot12TaskApplication.class, args);
}
}
3、創建一個service類 :AsyncService
@Service
public class AsyncService {
//告訴Spring這是一個異步方法
@Async
public void hello(){
try {
//休眠3秒
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("處理數據中...");
}
}
4、創建一個controller類:AsyncController
@RestController
public class AsyncController {
@Resource
AsyncService asyncService;
@GetMapping("/hello")
public String hello(){
asyncService.hello();
return "success";
}
}
5、運行測試
總結:
- 不使用異步注解,方法會休眠3秒在運行
- 使用異步注解,方法會直接被運行