异步任务
创建一个service类
@Service public class AsyncService { //通过@Async注解,告诉Spring,这是一个异步的方法 @Async public String hello(){ try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } return "数据正在处理..."; } }
创建一个controller控制类
@RestController public class AsyncController { ? @Autowired//自动装配,----导入我们的已知的一个类,并创建一个对象 AsyncService asyncService; @RequestMapping("/hello") public String hello(){ String str = asyncService.hello();//调用多线程类的hello()方法,效果是停止3秒,并输出"数据正在处理..." return str+"<hr>"+"OK!"; } }
在主方法中开启异步
@EnableAsync//开启多线程----异步注解功能 @SpringBootApplication public class Springboot08TestApplication { ? public static void main(String[] args) { SpringApplication.run(Springboot08TestApplication.class, args); } }
原文:https://www.cnblogs.com/hzw6118/p/13769536.html