版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/z_demon801/article/details/80758436
1. 在程序入口加入开启异步标签
@EnableAsync
2. 在需要执行异步的类中加入标签 (工具类)
package com.example.utils;
import java.util.concurrent.Future;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
@Component
public class AsyncUtil {
@Async
public Future<Boolean> doAsync1() throws Exception{
long start = System.currentTimeMillis();
Thread.sleep(1000);
long end = System.currentTimeMillis();
System.out.println("任务1耗时:"+ (end - start) + "毫秒");
return new AsyncResult<>(true);
}
@Async
public Future<Boolean> doAsync2() throws Exception{
long start = System.currentTimeMillis();
Thread.sleep(700);
long end = System.currentTimeMillis();
System.out.println("任务2耗时:"+ (end - start) + "毫秒");
return new AsyncResult<>(true);
}
@Async
public Future<Boolean> doAsync3() throws Exception{
long start = System.currentTimeMillis();
Thread.sleep(600);
long end = System.currentTimeMillis();
System.out.println("任务3耗时:"+ (end - start) + "毫秒");
return new AsyncResult<>(true);
}
}
3.测试
package com.example.controller;
import java.util.concurrent.Future;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.domain.model.UserInfo;
import com.example.domain.service.IUserInfoService;
import com.example.utils.AsyncUtil;
@RestController
@RequestMapping("/welcome")
public class WelcomeController {
@Autowired
private IUserInfoService iUserInfoService;
@Autowired
private AsyncUtil asyncUtil;
@RequestMapping("/user")
public String user() throws Exception {
long start = System.currentTimeMillis();
Future<Boolean> a = asyncUtil.doAsync1();
Future<Boolean> b = asyncUtil.doAsync2();
Future<Boolean> c = asyncUtil.doAsync3();
while(!a.isDone() || !b.isDone() || !c.isDone()) {
if(a.isDone() && b.isDone() && c.isDone()) {
break;
}
}
long end = System.currentTimeMillis();
System.out.println("任务全部完成。总耗时:"+ (end - start) + "毫秒!");
UserInfo user = iUserInfoService.getUserById(917);
return user.getUserNickName();
}
}
4.输出结果
任务3耗时:600毫秒
任务2耗时:700毫秒
任务1耗时:1000毫秒
任务全部完成。总耗时:1018毫秒!
如果去掉标签 输出结果为
任务1耗时:1000毫秒
任务2耗时:700毫秒
任务3耗时:600毫秒
任务全部完成。总耗时:2301毫秒!
5.使用场景
大部分会应用于
发送短信息, 发送邮件, App消息推送, 节省运维凌晨发布任务时间,提供效率