springboot 异步任务
在主类开始任务
package com.sugon.dataexchangeplatform;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@EnableAsync //开启异步注解功能
@SpringBootApplication
public class DataExChangePlatformApplication {
public static void main(String[] args) {
SpringApplication.run(DataExChangePlatformApplication.class, args);
}
}
使用异步
@Service
public class AsyncService {
@Async //告诉Spring这是一个异步的方法
public void hello(){
try {
Thread.sleep(5000);//休眠5s
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理...");
}
}
调用
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@RequestMapping("/hello")
public String hello(){
asyncService.hello(); //执行业务层hello方法:停止5s
return "hello";
}
}
本文来自博客园,作者:vx_guanchaoguo0,转载请注明原文链接:https://www.cnblogs.com/guanchaoguo/p/17116947.html