springboot-異步任務
簡單測試使用
異步任務可以簡單了解為 前端先立刻傳回OK之類的已經做完的資訊 然後後端還在運作任務
編寫service類 并通過注解告訴springboot為異步任務
package com.jie.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsynService {
//告訴springboot這是一個異步方法
@Async
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("資料正在處理");
}
}
package com.jie.controller;
import com.jie.service.AsynService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AsynController {
@Autowired
AsynService asynService;
@RequestMapping("/hello")
public String hello(){
asynService.hello();
return "ok";
}
}
package com.jie;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
//開啟異步功能
@EnableAsync
@SpringBootApplication
public class SpringbootAsynApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootAsynApplication.class, args);
}
}