关键所在:
1,protobuf-socket-rpc使用的是短连接,发送完成后,则需要将socket上行关闭
2,rpc.proto文件要统一
class NettyRpcPipelineFactory implements ChannelPipelineFactory {
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline p = Channels.pipeline();
// p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(MAX_FRAME_BYTES_LENGTH, 0, 4, 0, 4));
p.addLast("protobufDecoder", new ProtobufDecoder(defaultInstance));
// p.addLast("frameEncoder", new LengthFieldPrepender(4));
p.addLast("protobufEncoder", new ProtobufEncoder());
p.addLast("handler", handlerFactory.getChannelUpstreamHandler());
return p;
}
}
public class NettyRpcClientChannelUpstreamHandler extends SimpleChannelUpstreamHandler {
@Override
public void writeComplete(ChannelHandlerContext ctx, WriteCompletionEvent e) {
try {
NioSocketChannel ch = (NioSocketChannel) e.getChannel();
DefaultSocketChannelConfig cfg = (DefaultSocketChannelConfig) ch
.getConfig();
Field f = DefaultSocketChannelConfig.class
.getDeclaredField("socket");
f.setAccessible(true);
Socket socket = (Socket) f.get(cfg);
socket.shutdownOutput();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
3, protobuf-socket-rpc不支持分片发送,对数据较大的数据包,3K以上,建议使用netty-probuf-rpc提供的rpc实现
4,无网络时,会造成netty阻塞,改动方法如下:
public Message callBlockingMethod(MethodDescriptor method,RpcController controller, Message request, Message responsePrototype)
throws ServiceException {
BlockingRpcCallback callback = new BlockingRpcCallback();
ResponsePrototypeRpcCallback rpcCallback = new ResponsePrototypeRpcCallback(controller, responsePrototype, callback);
int nextSeqId = handler.getNextSeqId();
Message Request = buildRequest(method, request);
handler.registerCallback(nextSeqId, rpcCallback);
ChannelFuture future = this.channel.write(Request);
try {
future.sync();
}
catch (InterruptedException e1) {
e1.printStackTrace();
}
synchronized(callback) {
while(!callback.isDone()) {
try {
callback.wait();
} catch (InterruptedException e) {
logger.warn("Interrupted while blocking", e);
/* Ignore */
}
}
}
...
}