- @Async //告诉Spring 这是一个异步方法
- @EnableAsync //开启异步注解功能
编写service层
@Service
public class AsyncService {
//告诉Spring 这是一个异步方法
@Async
public void hello(){
try{
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理");
}
}
编写controller层
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@GetMapping("/hello")
public String hello(){
asyncService.hello();
return "ok";
}
}
在启动类中开启异步功能
@EnableAsync //开启异步注解功能
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
前台能瞬间访问页面,后台需要等待三秒接收数据


本文介绍如何在Spring框架中使用@Async注解实现异步方法,通过具体示例展示了在service和controller层的异步处理,以及如何在启动类中开启异步功能,使前台访问快速响应,后台任务延迟执行。
374

被折叠的 条评论
为什么被折叠?



