CountDownLatch实现异步转同步

异步转同步

    public Tip pushMsgByRedIdsWithNode(List<String> regIds, String msg) {

        String url = ydPropertites.getNode().getUrl();
        Tip tip = SuccessTip.SUCCESS_TIP;
        try {
            if (socket == null || !socket.connected()) {
                socket = IO.socket(url).connect();
                log.info("Socket.IO断开,重连:{}", socket);
            } else {
                log.info("Socket.IO连接复用:{}", socket);
            }

            NodePush nodePush = createNodePush(regIds, msg);//待发送的消息

            //使用Socket.io 发送

            Socket finalSocket = socket;
            String param = JsonUtils.obj2Json(nodePush);
            log.info("待推送数据:{}", param);
            socket.on("conn", args -> {

                log.info("已连接");
//                finalSocket.emit("pushMessage", param);

//                finalSocket.on("pushReceive", args1 -> log.info("调用结果:\n{}", args1[0]));
            });

            finalSocket.emit("pushMessage", param);

            CountDownLatch countDownLatch = new CountDownLatch(1);
            final Map<Boolean, String> resMap1 = new HashMap<>();
            finalSocket.on("pushReceive", args1 -> {
                log.info("调用结果:\n{}", args1[0]);//{"msg":"Ef-lJrMN8VQn7C1pAAAG该用户未登陆","code":500}
                Map<String, Object> resMap = JsonUtils.jsonStr2Obj(args1[0].toString(), Map.class);
                int count = (int) resMap.get("code");
                if (count != 200) {
                    resMap1.put(false, (String) resMap.get("msg"));
                }
                countDownLatch.countDown();
            });

            countDownLatch.await();
            log.info("本次推送结束");
            if (resMap1.get(false) != null) {
                tip = new ErrorTip(500, resMap1.get(false));
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            tip = new ErrorTip(500, e.getMessage());
        }
        return tip;
    }

猜你喜欢

转载自blog.csdn.net/m0_37208669/article/details/84799548