springboot開啟異步任務(wù)只需要兩個注解:@EnableAsync和@Async。
springboot啟動類上添加@EnableAsync注解來使springboot支持異步
@Async可以添加在類上,也可添加在方法上寇蚊。如果注解在類級別帮碰,則表明該類所有的方法都是異步方法蔗候,而這里的方法自動被注入使用ThreadPoolTaskExecutor作為TaskExecutor。
需要注意的是@Async并不支持用于被@Configuration注解的類的方法上。同一個類中,一個方法調(diào)用另外一個有@Async的方法空盼,注解也是不會生效的。
啟動類
package com.example.bootonly;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
// 使spring boot支持異步
@EnableAsync
public class BootOnlyApplication {
public static void main(String[] args) {
SpringApplication.run(BootOnlyApplication.class, args);
}
}
異步方法類
package com.example.bootonly.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
/**
* @author liujy
* @description 異步方法
* @since 2021-03-17 14:33
*/
// 這個類中的方法都是異步方法
@Async
@Slf4j
@Service
public class TaskService {
public void s() throws InterruptedException {
System.out.println("異步任務(wù)start");
// 代替業(yè)務(wù)代碼
Thread.sleep(10000);
System.err.println(Thread.currentThread().getName());
System.out.println("異步任務(wù)end");
}
}
Controller
package com.example.bootonly.test;
import com.example.bootonly.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author liujy
* @description
* @since 2021-03-17 14:45
*/
@RestController
public class TaskTest {
@Autowired
private TaskService taskService;
@RequestMapping("/task")
public String task() throws InterruptedException {
System.out.println("controller start");
taskService.s();
System.out.println("controller end");
return "success";
}
}
啟動項目新荤,用瀏覽器發(fā)起請求揽趾,可以多請求幾次,發(fā)現(xiàn)可以立即返回success苛骨。
測試
而異步任務(wù)隨后陸續(xù)完成:
測試結(jié)果