netty-protobuf-rpc与protobuf-socket-rpc互通

本文介绍了protobuf-socket-rpc的使用注意事项,包括短连接管理、protobuf定义文件一致性及分片发送限制等内容,并针对网络不可用时的阻塞问题提出了改进方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关键所在:

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 */
		}
	   }
	}
...
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值