1.使用Runnable异步处理Rest服务
@RequestMapping("/order")
public Callable order() {
logger.info("主线程开始");
Callable<String> result = new Callable<String>() {
@Override
public String call() throws Exception {
logger.info("副线程开始");
Thread.sleep(1000);
logger.info("副线程返回");
return "success";
}
};
logger.info("主线程返回");
return result;
}
执行结果如下:
我们可以看到,主线程几乎不占用时间,只是去调一下副线程就立马结束,就可以去做别的了,几乎不占用时间。
2.使用DeferredResult异步处理Rest服务
因为Runnable 的异步处理还是依赖于主线程的调用,实际上不满足我们企业中的应用,我们现实中往往是两个应用程序,非同一个进程。如下图所示:线程1和线程2是完全隔离的,不存在调用关系。此时就需要用到DeferredResult去进行异步处理了
1)模拟消息队列MockQueue对象
@Component
public class MockQueue {
private Logger logger = LoggerFactory.getLogger(MockQueue.class);
//下单消息
private String placeOrder;
//订单完成消息
private String completeOrder;
public String getPlaceOrder() {
return placeOrder;
}
public void setPlaceOrder(String placeOrder) {
//模拟下单后的处理,鸡模拟应用2
new Thread(() ->{
logger.info("接到下单请求,"+placeOrder);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.completeOrder = placeOrder;
logger.info("下单请求处理完毕,"+placeOrder);
}).start();
}
public String getCompleteOrder() {
return completeOrder;
}
public void setCompleteOrder(String completeOrder) {
this.completeOrder = completeOrder;
}
}
2)传递DeferredResult对象
/**
* 在线程1和线程2之间传递DeferredResult对象
*/
@Component
public class DeferredResultHolder {
//map的key就是订单号,value就是每个订单的处理结果
private Map<String, DeferredResult<String>> map = new HashMap<String, DeferredResult<String>>();
public Map<String, DeferredResult<String>> getMap() {
return map;
}
public void setMap(Map<String, DeferredResult<String>> map) {
this.map = map;
}
}
3)模拟下单以及生产消息
@RestController
public class AsyncController {
private Logger logger = LoggerFactory.getLogger(AsyncController.class);
@Autowired
private DeferredResultHolder deferredResultHolder;
@Autowired
private MockQueue mockQueue;
@RequestMapping("/order")
public DeferredResult<String> order() throws InterruptedException {
logger.info("主线程开始");
//随机生成8位的订单号
String oderNumber = RandomStringUtils.randomNumeric(8);
//模拟放进消息队列
mockQueue.setPlaceOrder(oderNumber);
//订单处理结果
DeferredResult<String> result = new DeferredResult<>();
deferredResultHolder.getMap().put(oderNumber,result);
// Callable<String> result = new Callable<String>() {
// @Override
// public String call() throws Exception {
// logger.info("副线程开始");
// Thread.sleep(1000);
// logger.info("副线程返回");
// return "success";
// }
// };
logger.info("主线程返回");
return result;
}
}
4)模拟监听器消费消息
/**
* 模拟线程2对于消息队列的监听,即查看completeOrder是否有值
*/
@Component
public class QueueListener implements ApplicationListener<ContextRefreshedEvent> {
private Logger logger = LoggerFactory.getLogger(QueueListener.class);
@Autowired
private DeferredResultHolder deferredResultHolder;
@Autowired
private MockQueue mockQueue;
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
//因为一直在循环,需要单开一个线程,不然启动的时候会阻塞
new Thread(() -> {
while(true) {
if(StringUtils.isNotBlank(mockQueue.getCompleteOrder())) {
String orderNumber = mockQueue.getCompleteOrder();
logger.info("返回订单处理结果:"+orderNumber);
//整个异步处理完成,设置返回给浏览器的信息
deferredResultHolder.getMap().get(orderNumber).setResult("place order success");
mockQueue.setCompleteOrder(null);
} else {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}