使用netty自带连接池,异步发送消息,同步获取返回结果

Netty获取异步执行结果

 // 定义个存储响应消息的变量responseMsgCache 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
demo演示结果
使用netty自带连接池,异步发送消息,同步获取返回结果

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

相关文章