Netty客户端同步获取结果

上次服务间通信是异步的,现在想实现客户端同步拿到服务端响应结果。实现如下:
在NettyClientHandler类中增加一个结果缓存器

 Map> resultMap = new ConcurrentHashMap<>();

修改方法

@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext,Protocol o) throws Exception {
    logger.info("channelRead0--------------"+Thread.currentThread().getName());
    logger.info("消费者接收到的消息为{}", JSONObject.toJSONString(o));
    resultMap.put(o.getId(),o);
}
public Protocol sendMsg(Protocol message){
        channel.writeAndFlush(message);
        while (true){
            Protocol remove = resultMap.remove(message.getId());
            if(remove!=null){
                return remove;
            }
        }
    }

测试类

public class NettyTest {

    public static void main(String[] args) {

        new Thread(()->{
            NettyServer.startNettyServer();
        }).start();

        new Thread(()->{
            NettyClient instance = NettyClient.getInstance();
            try {
                while (true){
                    Thread.sleep(2000);
                    Protocol protocol = new Protocol<>();
                    protocol.setMsgType((short)1);
                    RequestMsg requestMsg = new RequestMsg();
                    requestMsg.setMsg("hello:"+System.currentTimeMillis());
                    requestMsg.setOther("你好啊");
                    protocol.setBody(requestMsg);
                    Protocol responseMsgProtocol = instance.sendMsg(protocol);
                    System.out.println("同步获取到结果:"+ responseMsgProtocol);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }).start();
    }
}

Netty客户端同步获取结果_第1张图片

你可能感兴趣的:(java,开发语言)