前言
实际开发中,大多数的service都是同步执行并返回的,但有些特殊情况,我们是不需要马上得到返回结果,例如:数据量较大的报表统计,可能会执行一两个小时,我们只需要开一个异步任务即可,spring也为我们提供了这样的方式,下面我们来看一看他的实现
参考项目:https://github.com/bigbeef/cppba-sample
开源地址:https://github.com/bigbeef
个人博客:http://blog.cppba.com
注意:框架采用spring-boot,配置和启动类就不列出了,需要了解的可以看下面的参考项目,下面只提供核心代码
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";
}
}
运行项目
项目启动,浏览器访问http://127.0.0.1:8080/start,控制台打印出一下内容:
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!
很明显,程序并没有按照我们的调用顺序执行,说明我们的异步服务开启成功!
网友评论