Spring Boot使用@Async异步多个结果集合并

以我的搜索功能为例,多个搜索结果合并

异步类:AsyncService

import java.util.concurrent.Future;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

@Service
public class AsyncService {
	/**
	 * 应用搜索-异步
	 */
	@Async
	public Future<String> searchAppInfo() throws Exception{
		//自己的业务逻辑
				
		//睡眠3秒测试		
		Thread.sleep(3000);	
		
		String result = null;
		return new AsyncResult<String>(result);
	}
	
	/**
	 * 待办搜索-异步
	 */
	@Async
	public Future<String> searchPending() throws Exception{
		//自己的业务逻辑
				
		//睡眠1秒测试		
		Thread.sleep(1000);	
		
		String result = null;
		return new AsyncResult<String>(result);
	}
	
	/**
	 * 用户搜索-异步
	 */
	@Async
	public Future<String> searchUser() throws Exception{
		//自己的业务逻辑
				
		//睡眠2秒测试		
		Thread.sleep(2000);	
		
		String result = null;
		return new AsyncResult<String>(result);
	}
}

业务类:CompositeService

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CompositeService {
	@Autowired
    private AsyncService asyncService;
	
	/**
	 * 综合搜索集合
	 */
	public Map<String, String> searchList() {
		try {
			long beforeTime = System.currentTimeMillis();// 开始时间戳
			
			//应用搜索-异步
			Future<String> appResult = asyncService.searchAppInfo();
			//待办搜索-异步
			Future<String> pendingResult = asyncService.searchPending();
			//用户搜索-异步
			Future<String> userResult = asyncService.searchUser();

			
			//添加结果集,30秒超时
			Map<String, String> jsonObject = new HashMap<String, String>();
			if(appResult != null){
				jsonObject.put("AppInfo", appResult.get(30, TimeUnit.SECONDS));
			}
			if(pendingResult != null){
				jsonObject.put("AppPending", pendingResult.get(30, TimeUnit.SECONDS));
			}
			if(userResult != null){
				jsonObject.put("UnifiedUser", userResult.get(30, TimeUnit.SECONDS));
			}
			
			long afterTime = System.currentTimeMillis();// 结束时间戳
			//耗时3秒多正确,耗时6秒多异步未成功
			System.out.println("耗时"+(afterTime - beforeTime)+"毫秒");
			
			return jsonObject;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}	
	}
}

调用测试:ControllerTest

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.async.service.CompositeService;

/**
 * 测试异步任务
 */
@RestController
public class ControllerTest {
    @Autowired
    private CompositeService compositeService;
    
    @GetMapping("/test")
    public String test(){
        compositeService.searchList();
        return "异步测试...............";
    }
}

打印结果,应该为3秒多,因为休眠的时间最长的一个方法是3秒

耗时3011毫秒

如果有打印出6秒多,证明有问题,实在解决不了的,可以使用笨一点的办法,修改业务类CompositeService代码

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CompositeService {
	@Autowired
    private AsyncService asyncService;
	
	/**
	 * 综合搜索集合
	 */
	public Map<String, String> searchList() {
		try {
			long beforeTime = System.currentTimeMillis();// 开始时间戳
			
			//应用搜索-异步
			Future<String> appResult = asyncService.searchAppInfo();
			//待办搜索-异步
			Future<String> pendingResult = asyncService.searchPending();
			//用户搜索-异步
			Future<String> userResult = asyncService.searchUser();

			//循环判断所有异步方法是否执行完毕
			long beforeTime1 = System.currentTimeMillis();// 开始时间戳
			while (true) {
				//执行完毕跳出循环
				if((appResult == null || appResult.isDone()) 
						&& (pendingResult == null || pendingResult.isDone())
						&& (userResult == null || userResult.isDone())){
					break;
				}
				//超时跳出循环
				long afterTime1 = System.currentTimeMillis();// 结束时间戳
				if((afterTime1 - beforeTime1) > 30000){	//30秒
					break;
				}
				Thread.sleep(20);	//每隔20毫秒执行一次
			}
			
			//添加结果集,30秒超时
			Map<String, String> jsonObject = new HashMap<String, String>();
			if(appResult != null){
				jsonObject.put("AppInfo", appResult.get());
			}
			if(pendingResult != null){
				jsonObject.put("AppPending", pendingResult.get());
			}
			if(userResult != null){
				jsonObject.put("UnifiedUser", userResult.get());
			}
			
			long afterTime = System.currentTimeMillis();// 结束时间戳
			//耗时3秒多正确,耗时6秒多异步未成功
			System.out.println("耗时"+(afterTime - beforeTime)+"毫秒");
			
			return jsonObject;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}	
	}
}

使用循环判断Future类自带的方法isDone()判断是否执行完毕

//循环判断所有异步方法是否执行完毕
			long beforeTime1 = System.currentTimeMillis();// 开始时间戳
			while (true) {
				//执行完毕跳出循环
				if((appResult == null || appResult.isDone()) 
						&& (pendingResult == null || pendingResult.isDone())
						&& (userResult == null || userResult.isDone())){
					break;
				}
				//超时跳出循环
				long afterTime1 = System.currentTimeMillis();// 结束时间戳
				if((afterTime1 - beforeTime1) > 30000){	//30秒
					break;
				}
				Thread.sleep(20);	//每隔20毫秒执行一次
			}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

涛哥是个大帅比

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值