前言
實(shí)際開發(fā)中,大多數(shù)的service都是同步執(zhí)行并返回的雾消,但有些特殊情況,我們是不需要馬上得到返回結(jié)果挫望,例如:數(shù)據(jù)量較大的報(bào)表統(tǒng)計(jì)立润,可能會(huì)執(zhí)行一兩個(gè)小時(shí),我們只需要開一個(gè)異步任務(wù)即可媳板,spring也為我們提供了這樣的方式桑腮,下面我們來看一看他的實(shí)現(xiàn)
參考項(xiàng)目:https://github.com/bigbeef/cppba-sample
開源地址:https://github.com/bigbeef
個(gè)人博客:http://blog.cppba.com
注意:框架采用spring-boot,配置和啟動(dòng)類就不列出了蛉幸,需要了解的可以看下面的參考項(xiàng)目破讨,下面只提供核心代碼
StartService.java
package com.cppba.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class StartService {
@Async
public void taskSayHi(Integer i) {
System.out.println("hi! No. " + i + "!");
}
@Async
public void taskSayHello(Integer i) {
System.out.println("hello! No. " + i + "!");
}
}
StartController.java
package com.cppba.controller;
import com.cppba.service.StartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@EnableAsync
public class StartController {
@Autowired
private StartService startService;
@RequestMapping("/start")
@ResponseBody
public String start(){
Integer count = 10;
for (Integer i = 1; i <= count; i++) {
startService.taskSayHi(i);
startService.taskSayHello(i);
}
return "success";
}
}
運(yùn)行項(xiàng)目
項(xiàng)目啟動(dòng),瀏覽器訪問http://127.0.0.1:8080/start,控制臺(tái)打印出一下內(nèi)容:
No.1,hello!
No.10,hi!
No.7,hi!
No.8,hello!
No.6,hi!
No.10,hello!
No.7,hello!
No.5,hi!
No.1,hi!
No.6,hello!
No.4,hi!
No.8,hi!
No.5,hello!
No.3,hi!
No.9,hello!
No.4,hello!
No.2,hi!
No.9,hi!
No.3,hello!
No.2,hello!
很明顯奕纫,程序并沒有按照我們的調(diào)用順序執(zhí)行提陶,說明我們的異步服務(wù)開啟成功!