上次服务间通信是异步的,现在想实现客户端同步拿到服务端响应结果。实现如下:
在NettyClientHandler类中增加一个结果缓存器
Map<Long,Protocol<ResponseMsg>> resultMap = new ConcurrentHashMap<>();
修改方法
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext,Protocol<ResponseMsg> o) throws Exception {
logger.info("channelRead0--------------"+Thread.currentThread().getName());
logger.info("消费者接收到的消息为{}", JSONObject.toJSONString(o));
resultMap.put(o.getId(),o);
}
public Protocol<ResponseMsg> sendMsg(Protocol<RequestMsg> message){
channel.writeAndFlush(message);
while (true){
Protocol<ResponseMsg> 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<RequestMsg> protocol = new Protocol<>();
protocol.setMsgType((short)1);
RequestMsg requestMsg = new RequestMsg();
requestMsg.setMsg("hello:"+System.currentTimeMillis());
requestMsg.setOther("你好啊");
protocol.setBody(requestMsg);
Protocol<ResponseMsg> responseMsgProtocol = instance.sendMsg(protocol);
System.out.println("同步获取到结果:"+ responseMsgProtocol);
}
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
}