netty客户端同步请求实现
在项目开发中经常会遇到某个请求需要立刻返回结果的请,而我们使用的框架netty是异步的,如何做到同步请求是经常会困惑到刚刚接触netty的同行。
本文使用netty4为标准实现客户端向服务器的同步请求实例。如有不合理之处望各位指正,共同进步。
客户端 SimpleChatClientHandler
package com.netty.chart;
import java.util.concurrent.CountDownLatch;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
public class SimpleChatClientHandler extends SimpleChannelInboundHandler<String> {
private CountDownLatch lathc;
public SimpleChatClientHandler(CountDownLatch lathc) {
this.lathc = lathc;
}
private String result;
@Override
protected void channelRead0(ChannelHandlerContext arg0, String arg1) throws Exception {
System.out.println("==========收到服务器消息:"+arg1);
result = arg1;
lathc.countDown();//消息收取完毕后释放同步锁
}
public void resetLatch(CountDownLatch initLathc){
this.lathc = initLathc;
}
public String getResult() {
return result;
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
// IdleStateHandler 所产生的 IdleStateEvent 的处理逻辑.
if (evt instanceof IdleStateEvent) {
IdleStateEvent e = (IdleStateEvent) evt;
switch (e.state()) {
case ALL_IDLE:
handleAllIdle(ctx);
break;
default:
break;
}
}
}
protected void handleAllIdle(ChannelHandlerContext ctx) {