国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

Java如何使用ReentrantLock實現長輪詢

瀏覽:3日期:2022-08-14 16:52:13
Java代碼1. ReentrantLock

加鎖阻塞,一個condition對應一個線程,以便于喚醒時使用該condition一定會喚醒該線程

/** * 獲取探測點數據,長輪詢實現 * @param messageId * @return */ public JSONObject getToutData(String messageId) {Message message = toutMessageCache.get(messageId);if (message == null) { // 等待 lock.lock(); try {Condition condition = lock.newCondition();conditionMap.put(messageId + '_data', condition);condition.await(CONNECTION_HOLD_TIMEOUT, TimeUnit.SECONDS); // 等待60s } catch (InterruptedException e) {// 等待超時, do nothing } finally {lock.unlock(); }}// 再次嘗試獲取message = toutMessageCache.get(messageId);if (message == null) { // 如果還沒有, 返回空對象 return null;}byte[] bytes = message.getDataBytes();if (bytes == null) { return null;}String resStr = new String(bytes, StandardCharsets.UTF_8);//log.info('resStr: {}', resStr);JSONObject resObj;try { resObj = new JSONObject(resStr); resObj.put('invokeTime', DateUtil.format(new Date(resObj.getLong('invokeTime')), DatePattern.NORM_DATETIME_MS_PATTERN));} catch (Exception e) { resObj = new JSONObject();}return resObj; }2. 回調

當異步數據返回,使用上一步的condition喚醒線程

public void callback(Message message) { String messageId = message.getId(); toutMessageCache.put(message.getId(), message); String messageDataId = messageId + '_data'; if (conditionMap.containsKey(messageDataId)) {lock.lock();try { Condition condition = conditionMap.get(messageDataId); condition.signal();} catch (Exception e) { e.printStackTrace();} finally { lock.unlock(); conditionMap.remove(messageDataId);} }}3. 喚醒

執行回調操作

public void distribute(Message message, ChannelHandlerContext ctx) { MessageType messageType = message.getMessageType(); switch (messageType) { case TOUT_DATA_RESPONSE: // 數據響應 toutService.callback(message); break; }}4. 調用

調用時,判斷返回的值是否為空,如果為空,與前端約定,當返回該狀態值時,應再次發起相同請求

/*** 獲取探測數據(使用長輪詢實現)* @param linkId* @return*/@GetMapping('/data')public ResultVO getToutData(String linkId) { JSONObject resObj = toutService.getToutData(linkId); if (resObj == null || resObj.isEmpty()) { return ResultVOUtil.error(ResultEnum.NO_MESSAGE_HOLD_CONNECTION); } return ResultVOUtil.success(resObj);}5.前端實現

簡單使用遞歸實現了當數據返回無效時再次發起請求

let that = thisfunction getData() { if (toutStatus === statusEnum.start) { getToutData({ linkId }).then(res => { if (res.code === ERROR_CODE_OK) { that.toutData = res.data toutStatus = statusEnum.resData that._btnStatus() } else { getData() } }) } } // 遞歸循環調用 getData()

以上就是如何使用ReentrantLock實現長輪詢的詳細內容,更多關于ReentrantLock長輪詢的資料請關注好吧啦網其它相關文章!

標簽: Java
相關文章:
主站蜘蛛池模板: 福建省| 晋江市| 芜湖市| 交口县| 柘城县| 铁岭市| 奈曼旗| 汝阳县| 神木县| 莲花县| 岐山县| 高淳县| 翁牛特旗| 肃北| 福鼎市| 绩溪县| 日土县| 苍南县| 长白| 漯河市| 阿图什市| 聊城市| 彰化市| 吴忠市| 潞西市| 安泽县| 遵化市| 大余县| 关岭| 高陵县| 阿合奇县| 视频| 广州市| 黎平县| 江油市| 新野县| 布拖县| 玉田县| 溧阳市| 汕头市| 六安市|