当我们有两个不相干的任务A,B
A 调用了B ,B 需要执行很长时间,而A不用等待可以直接往后继续执行。那么我们可以把B设置为异步任务。B执行,同时A继续往后执行。
步骤
-
开启异步
在入口处使用注解:@EnableAsync
-
标记异步
@Async对应方法或者类
package com.wang.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
/**
* 异步任务
* 注解开启 @EnableAsync
* 标注为一个定时任务 @Async
*/
@Service
public class AsyncService {
// 调用这个方法,调用者可以继续执行
@Async
public void asyncOperator() throws InterruptedException {
// 等待30秒
Thread.sleep(30000);
System.out.println("不用等我");
}
public void notAsncOperator() throws InterruptedException {
Thread.sleep(30000);
System.out.println("需要等我醒来");
}
}
-
测试异步
前台有两个任务,分别调用:异步和非异步
package com.wang.controller;
import com.wang.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class AsncController {
@Autowired
private AsyncService asyncService;
@RequestMapping("/async")
@ResponseBody
public String asyncOperator() throws InterruptedException {
asyncService.asyncOperator();
return "我没等待另一个方法执行就返回了";
}
@RequestMapping("/notAsync")
@ResponseBody
public String notAsync() throws InterruptedException {
asyncService.notAsncOperator();
return "我一直在等,等待另一个方法执行才返回的";
}
}
异步方法调用:
后台没有执行,页面就返回了
等待中。。。
http://localhost:8081/notAsync