SpringBoot 开启异步任务
第一步:方法上加@Async注解
@Service
public class AsyncService {
@Async
public void hello(){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("处理数据中...");
}
}
第二步:开启异步注解功能
@SpringBootApplication
@EnableAsync //开启异步注解功能
public class DemoSpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(DemoSpringbootApplication.class, args);
}
}
第三步:调用测试
测试地址:http://localhost:8080/hello
@RestController
public class AsyncController {
@Autowired
private AsyncService asyncService;
@GetMapping("/hello")
public String hello(){
asyncService.hello();
return "success";
}
}