关键所在:
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 */
}
}
}
...
}
本文介绍了protobuf-socket-rpc的使用注意事项,包括短连接管理、protobuf定义文件一致性及分片发送限制等内容,并针对网络不可用时的阻塞问题提出了改进方案。
342

被折叠的 条评论
为什么被折叠?



