一、定义异步服务
package com.cn.laoluobase.services;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
@Service
public class AsyncService {
/**
* 在Spring中,基于@Async标注的方法,称之为异步方法;
* 这些方法将在执行的时候,将会在独立的线程中被执行,调用者无需等待它的完成,即可继续其他的操作。
* 调用示例:controller中使用@EnableAsync注解标注,然后直接执行方法()即可执行:
* @Autowired
* AsyncService asyncService = new AsyncService();
* asyncService.hello();
*/
@Async
public void hello(){
try {
System.out.println("异步模拟任务...开始");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("异步模拟任务...完成");
}
/**
* 异步执行函数,通用异步方法。
* * @Autowired
* * AsyncService asyncService = new AsyncService();
asyncService.asyncDo(map,m->{
System.out.println("开始");
try {
System.out.println("异步模拟任务...开始");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("异步模拟任务...完成1");
System.out.println(map);
return true;
});
*/
@Async
public void asyncDo(Map dataMap, Function function){
function.apply(dataMap);
}
}
二、异步服务调用
需要开启@EnableAsync注解。其他的就是正常的服务调用。
@RestController
@RequestMapping("/async")
@EnableAsync
public class AsyncServicesDemo {
@Resource
AsyncService asyncService ;
@RequestMapping(value = "/demo1",method = RequestMethod.GET)
public String get1(){
asyncService.hello();
System.out.println("程序结束,但异步程序还在继续");
return "RequestMapping with method=GET";
}
}