SpringBoot异步任务 @Async注解(四)
首先启动类,添加 @EnableAsync 注解开启异步任务:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@EnableAsync
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
然后写一个业务逻辑,在 proce() 方法中睡5秒表示执行了大量业务逻辑,在方法上添加@Async注解表示是一个异步方法:
package com.example.demo.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class TestService {
@Async
public void proce(){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.err.println("业务处理中。。。");
}
}
最后写一个接口 来调用上面的 proce() 方法,然后返回一个字符串到浏览器:
package com.example.demo.controller;
import com.example.demo.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class TestController {
@Autowired
TestService testService;
@GetMapping("/hello")
@ResponseBody
public String hello(){
testService.proce();
return "HelloWorld";
}
}
运行项目访问hello接口,可以发现浏览器立马就返回了结果,并没有等待5秒,这就是异步任务起了作用,proce()方法被异步执行了。