View Code
- 在反序列化过程中,需要指定要转化的类型,而服务端接收request,客户端接收response,二者类型是不一样的,所以在后续传输时指定类型
有了需要传输的数据后,使用Netty开启网络服务进行传输
服务端
===
绑定端口号,开启连接
public class ServerNetty {
public static void connect(int port) throws InterruptedException {
EventLoopGroup workGroup = new NioEventLoopGroup();
EventLoopGroup bossGroup = new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.channel(NioServerSocketChannel.class)
.group(bossGroup,workGroup)
.childHandler(new ChannelInitializer() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
/**
-
加入自定义协议的数据处理器,指定接收到的数据类型
-
加入服务端处理器
*/
ch.pipeline().addLast(new NettyProtocolHandler(RpcRequest.class));
ch.pipeline().addLast(new ServerHandler());
}
});
bootstrap.bind(port).sync();
}
}
Netty中绑定了两个数据处理器
一个是数据处理器,服务端接收到请求->调用方法->返回响应,这些过程都在数据处理器中执行
public class ServerHandler extends SimpleChannelInboundHandler {
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
RpcRequest rpcRequest = (RpcRequest)msg;
// 获取使用反射需要的各个参数
String methodName = rpcRequest.getMethodName();
Class[] paramTypes = rpcRequest.getParamType();
Object[] args = rpcRequest.getArgs();
String className = rpcRequest.getClassName();
//从注册中心容器中获取对象
Object object = Server.hashMap.get(className);
Method method = object.getClass().getMethod(methodName,paramTypes);
//反射调用方法
String result = (String) method.invoke(object,args);
// 将响应结果封装好后发送回去
RpcResponse rpcResponse = new RpcResponse();
rpcResponse.setCode(200);
rpcResponse.setResult(result);
ctx.writeAndFlush(rpcResponse);
}
}
- 这里从hash表中获取对象,有一个预先进行的操作:将有可能被远程调用的对象放入容器中,等待使用
一个是自定义的TCP协议处理器,为了解决TCP的常见问题:因为客户端发送的数据包和服务端接收数据缓冲区之间,大小不匹配导致的粘包、拆包问题。
/**
-
网络传输的自定义TCP协议
-
发送时:为传输的字节流添加两个魔数作为头部,再计算数据的长度,将数据长度也添加到头部,最后才是数据
-
接收时:识别出两个魔数后,下一个就是首部,最后使用长度对应的字节数组接收数据
*/
public class NettyProtocolHandler extends ChannelDuplexHandler {
private static final byte[] MAGIC = new byte[]{0x15,0x66};
private Class decodeType;
public NettyProtocolHandler() {
}
public NettyProtocolHandler(Class decodeType){
this.decodeType = decodeType;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf in = (ByteBuf) msg;
//接收响应对象
Object dstObject;
byte[] header = new byte[2];
in.readBytes(header);
byte[] lenByte = new byte[4];
in.readBytes(lenByte);
int len = ByteUtils.Bytes2Int_BE(lenByte);
byte[] object = new byte[len];
in.readBytes(object);
dstObject = JsonSerialization.deserialize(object, decodeType);
//交给下一个数据处理器
ctx.fireChannelRead(dstObject);
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
ByteBuf byteBuf = Unpooled.buffer();
//写入魔数
byteBuf.writeBytes(MAGIC);
byte[] object = JsonSerialization.serialize(msg);
//数据长度转化为字节数组并写入
int len = object.length;
byte[] bodyLen = ByteUtils.int2bytes(len);
byteBuf.writeBytes(bodyLen);
//写入对象
byteBuf.writeBytes(object);
ctx.writeAndFlush(byteBuf);
}
}
-
这个数据处理器是服务端和客户端都要使用的,就相当于是一个双方定好传输数据要遵守的协议
-
在这里进行了对象的序列化和反序列化,所以反序列化类型在这个处理器中指定
-
这里面要将数据的长度发送,需一个将整数类型转化为字节类型的工具
转化数据工具类
View Code
客户端
===
将Netty的操作封装了起来,最后返回一个Channle类型,由它进行发送数据的操作
public class ClientNetty {
public static Channel connect(String host,int port) throws InterruptedException {
InetSocketAddress address = new InetSocketAddress(host,port);
EventLoopGroup workGroup = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.channel(NioSocketChannel.class)
.group(workGroup)
.handler(new ChannelInitializer() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//自定义协议handler(客户端接收的是response)
ch.pipeline().addLast(new NettyProtocolHandler(RpcResponse.class));
//处理数据handler
ch.pipeline().addLast(new ClientHandler());
}
});
Channel channel = bootstrap.connect(address).sync().channel();
return channel;
}
}
数据处理器负责接收response,并将响应结果放入在future中,future的使用在后续的动态代理中
public class ClientHandler extends SimpleChannelInboundHandler {
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
RpcResponse rpcResponse = (RpcResponse) msg;
//服务端正常情况返回码为200
if(rpcResponse.getCode() != 200){
throw new Exception();
}
//将结果放到future里
RPCInvocationHandler.future.complete(rpcResponse.getResult());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
}
}
要让客户端在调用远程方法时像调用本地方法一样,就需要一个代理对象,供客户端调用,让代理对象去调用服务端的实现。
代理对象构造
public class ProxyFactory {
public static Object getProxy(Class<?>[] interfaces){
return Proxy.newProxyInstance(ProxyFactory.class.getClassLoader(),
interfaces,
new RPCInvocationHandler());
}
}
客户端代理对象的方法执行
将request发送给服务端后,一直阻塞,等到future里面有了结果为止。
public class RPCInvocationHandler implements InvocationHandler {
static public CompletableFuture future;
static Channel channel;
static {
future = new CompletableFuture();
//开启netty网络服务
try {
channel = ClientNetty.connect(“127.0.0.1”,8989);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
RpcRequest rpcRequest = new RpcRequest();
rpcRequest.setArgs(args);
rpcRequest.setMethodName(method.getName());
rpcRequest.setParamType(method.getParameterTypes());
rpcRequest.setClassName(method.getDeclaringClass().getSimpleName());
channel.writeAndFlush(rpcRequest);
//一个阻塞操作,等待网络传输的结果
String result = (String) future.get();
return result;
}
}
最后
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数Java工程师,想要提升技能,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助。
因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,不论你是刚入门Android开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门!
如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
入阿里一直到现在。**
深知大多数Java工程师,想要提升技能,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助。
因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
[外链图片转存中…(img-UW1nCod3-1715576292802)]
[外链图片转存中…(img-JOoIm0B2-1715576292803)]
[外链图片转存中…(img-vpy9qzw1-1715576292803)]
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,不论你是刚入门Android开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门!
如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!