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 searchAppInfo() throws Exception{
		//自己的业务逻辑
				
		//睡眠3秒测试		
		Thread.sleep(3000);	
		
		String result = null;
		return new AsyncResult(result);
	}
	
	/**
	 * 待办搜索-异步
	 */
	@Async
	public Future searchPending() throws Exception{
		//自己的业务逻辑
				
		//睡眠1秒测试		
		Thread.sleep(1000);	
		
		String result = null;
		return new AsyncResult(result);
	}
	
	/**
	 * 用户搜索-异步
	 */
	@Async
	public Future searchUser() throws Exception{
		//自己的业务逻辑
				
		//睡眠2秒测试		
		Thread.sleep(2000);	
		
		String result = null;
		return new AsyncResult(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 searchList() {
		try {
			long beforeTime = System.currentTimeMillis();// 开始时间戳
			
			//应用搜索-异步
			Future appResult = asyncService.searchAppInfo();
			//待办搜索-异步
			Future pendingResult = asyncService.searchPending();
			//用户搜索-异步
			Future userResult = asyncService.searchUser();

			
			//添加结果集,30秒超时
			Map jsonObject = new HashMap();
			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 searchList() {
		try {
			long beforeTime = System.currentTimeMillis();// 开始时间戳
			
			//应用搜索-异步
			Future appResult = asyncService.searchAppInfo();
			//待办搜索-异步
			Future pendingResult = asyncService.searchPending();
			//用户搜索-异步
			Future 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 jsonObject = new HashMap();
			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毫秒执行一次
			}

 

你可能感兴趣的:(Spring)