使用netty自帶連接池,異步發送消息,同步獲取返回結果


Netty獲取異步執行結果

	// 定義個存儲響應消息的變量responseMsgCache,使用Guava讓消息會自動過期
    private static Cache<String, BlockingQueue<String>> responseMsgCache = CacheBuilder.newBuilder()
            .maximumSize(50000)
            .expireAfterWrite(1000, TimeUnit.SECONDS)
            .build();

步驟:(具體代碼參考下面demo)

  1. 給消息設置個唯一key

  2. 初始化響應消息隊列:responseMsgCache.put(key,new LinkedBlockingQueue (1)); 見NettyTools.initReceiveMsg(key);

  3. 執行異步IO:future.addListener 見NettyClientService.sendMsg

  4. 阻塞等待:responseMsgCache.get(key).poll()見NettyTools.waitReceiveMsg(key);

  5. 處理事件:如果監聽到事件,responseMsgCache.get(key).add(Response)見NettyTools.setReceiveMsg(key, msgStr);

  6. 等待結束,返回response。

demo

git地址:https://gitee.com/xjmroot/netty-pool
效果如下:

參考:http://thoreauz.com/2019/01/19/rpc2-netty-handler/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM