Netty獲取異步執行結果
// 定義個存儲響應消息的變量responseMsgCache,使用Guava讓消息會自動過期
private static Cache<String, BlockingQueue<String>> responseMsgCache = CacheBuilder.newBuilder()
.maximumSize(50000)
.expireAfterWrite(1000, TimeUnit.SECONDS)
.build();
步驟:(具體代碼參考下面demo)
-
給消息設置個唯一key
-
初始化響應消息隊列:responseMsgCache.put(key,new LinkedBlockingQueue
(1)); 見NettyTools.initReceiveMsg(key);
-
執行異步IO:future.addListener
見NettyClientService.sendMsg
-
阻塞等待:responseMsgCache.get(key).poll()
見NettyTools.waitReceiveMsg(key);
-
處理事件:如果監聽到事件,responseMsgCache.get(key).add(Response)
見NettyTools.setReceiveMsg(key, msgStr);
-
等待結束,返回response。
demo
git地址:https://gitee.com/xjmroot/netty-pool
效果如下: