目标:Netty的自定义RPC,序列化协议为JSON,使用fastjson作为JSON框架,并根据RpcRequest实体作为通信协议,服务端需根据客户端传递过来的RpcRequest对象通过反射,动态代理等技术,最终能够执行目标方法,返回字符串"success"。
-
结构
分为三个模块:rpc-common 通用模块, rpc-consumer 客户端模块, rpc-my-provider客服端模块

-
rpc-common模块

1)接口public interface IUserService { public RpcResponse sayHello(String msg); }2)JSON序列化工具
public interface Serializer { /** * java对象转换为二进制 */ byte[] serialize(Object object) throws IOException; /** * 二进制转换成java对象 */ <T> T deserialize(Class<T> clazz, byte[] bytes) throws IOException; }public class JSONSerializer implements Serializer { @Override public byte[] serialize(Object object) { return JSON.toJSONBytes(object); } @Override public <T> T deserialize(Class<T> clazz, byte[] bytes) { return JSON.parseObject(bytes, clazz); } }3)定义编码和解码
public class RpcEncoder extends MessageToByteEncoder { private Class<?> clazz; private Serializer serializer; public RpcEncoder(Class<?> clazz, Serializer serializer) { this.clazz = clazz; this.serializer = serializer; } @Override protected void encode(ChannelHandlerContext channelHandlerContext, Object msg, ByteBuf byteBuf) throws Exception { if (clazz != null && clazz.isInstance(msg)) { byte[] bytes = serializer.serialize(msg); byteBuf.writeInt(bytes.length); byteBuf.writeBytes(bytes); } } }public class RpcDecoder extends ByteToMessageDecoder { private Class<?> clazz; private Serializer serializer; public RpcDecoder(Class<?> clazz, Serializer serializer) { this.clazz = clazz; this.serializer = serializer; } @Override protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception { // Check if there are at least 4 bytes readable if (byteBuf.readableBytes() >= 4) { int readInt = byteBuf.readInt(); System.out.println("ByteToIntegerDecoder decode msg is " + readInt); byte[] bytes = new byte[readInt]; byteBuf.readBytes(bytes); Object deserialize = serializer.deserialize(clazz, bytes); list.add(deserialize); } } }4)定义Request和Response实体组件
public class RpcRequest {

最低0.47元/天 解锁文章
1293

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



