netty用pb来实现多接口rpc

在netty中使用pb, nettty的pb编解码必须指定要解码和编码的pb结构体,这然做多接口的应用就很不方便,这里采用了一种简单的方式来解决。

pb定义如下:

package org.zhwen.netty.hello;

enum ReqestType {
LOGIN = 0;
SERVICE = 1;
}

message Request {
required ReqestType type = 1;
optional Login login = 100;
optional Service service = 101;
}

message Login {
required string user = 1;
required string pswd = 2;
}

message Service {
optional string content = 1;
}

message Response {
required ReqestType type = 1;
required int64 seqid = 2;
required int32 ret = 3;
optional string result = 4;
}

在server端这样写即可

pipeline.addLast(“protobufDecoder”, new ProtobufDecoder(Hello.Request.getDefaultInstance()));

protected void channelRead0(ChannelHandlerContext ctx, Request req) throws Exception {
Response.Builder response = Response.newBuilder();

response.setSeqid(++count);
response.setType(req.getType());

if (ReqestType.LOGIN == req.getType()) {
response.setResult(req.getLogin().getPswd());
response.setRet(0);

客户端写法也是这样,

pipeline.addLast(“protobufDecoder”, new ProtobufDecoder(Hello.Response.getDefaultInstance()));

处理也是类似的方式,因为服务端每次都把请求类型原封不动的返回给客户端,客户端也就可以根据server的返回处理不同的请求类型了。

这种方式简单易用,实现起来应该很方便。

Leave a Reply

Your email address will not be published. Required fields are marked *