异步处理rest服务

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;
}

执行结果如下:
1749972-20190831155732088-1379306056.png

我们可以看到,主线程几乎不占用时间,只是去调一下副线程就立马结束,就可以去做别的了,几乎不占用时间。

2.使用DeferredResult异步处理Rest服务

因为Runnable 的异步处理还是依赖于主线程的调用,实际上不满足我们企业中的应用,我们现实中往往是两个应用程序,非同一个进程。如下图所示:线程1和线程2是完全隔离的,不存在调用关系。此时就需要用到DeferredResult去进行异步处理了

1749972-20190831160116878-1484130554.png

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();
    }
}

运行结果:

1749972-20190831175936679-1831443422.png

3.异步处理配置

针对两种异步方式注册拦截器,不能像之前同步那样用addInterceptors

1749972-20190831180151603-128348399.png

转载于:https://www.cnblogs.com/qq-7895/p/11439954.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值