异步任务.
异步开启.
第一步
在需要异步处理的方法上添加
@Async
注解
@Service
public class AsyncService {
@Async
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("数据正在处理...");
}
}
第二步
在 程序入口类上添加
@EnableAsync
注解
@EnableAsync
@SpringBootApplication
public class TaskApplication {
public static void main(String[] args) {
SpringApplication.run(TaskApplication.class, args);
}
}
到这里 我们已经 完成了 开启异步
测试.
编写AsyncController
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@RequestMapping("/hello")
public String async(){
asyncService.hello();
return "OK";
}
}
localhost:8080/hello测试
发现 开启异步 很快就在页面上显示了 OK
localhost:8080/hello