异步任务
1、Service
package com.sw.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
/**
* @Author suaxi
* @Date 2020/12/26 15:57
*/
@Service
public class AsyncService {
//告诉Spring这是一个异步任务
@Async
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在加载...");
}
}
2、Controller
package com.sw.controller;
import com.sw.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Author suaxi
* @Date 2020/12/26 15:58
*/
@RestController
public class AsyncController {
@Autowired
private AsyncService asyncService;
@RequestMapping("/test")
public String hello(){
asyncService.hello();
return "Ok";
}
}
3、SpringBoot启动类开启异步任务的注解
package com.sw;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableAsync //开启异步任务注解
@SpringBootApplication
public class Springboot09AsynctaskApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot09AsynctaskApplication.class, args);
}
}
当用户执行/test
请求时,前端页面及时返回结果,同时异步任务延迟三秒在控制台打印输出结果
评论 (0)