《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》,点击传送门,即可获取!
服务端
===
绑定端口号,开启连接
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;
}
}
-
这里用static修饰future和channle,没有考虑到客户端去连接多个服务端和多次远程调用
-
可以使用一个hash表,存储与不同服务端对应的channle,每次调用时从hash表中获取即可
-
用hash表存储与不同request对应的future,每个响应的结果与之对应
客户端
===
最后
既已说到spring cloud alibaba,那对于整个微服务架构,如果想要进一步地向上提升自己,到底应该掌握哪些核心技能呢?
就个人而言,对于整个微服务架构,像RPC、Dubbo、Spring Boot、Spring Cloud Alibaba、Docker、kubernetes、Spring Cloud Netflix、Service Mesh等这些都是最最核心的知识,架构师必经之路!下图,是自绘的微服务架构路线体系大纲,如果有还不知道自己该掌握些啥技术的朋友,可根据小编手绘的大纲进行一个参考。
如果觉得图片不够清晰,也可来找小编分享原件的xmind文档!
且除此份微服务体系大纲外,我也有整理与其每个专题核心知识点对应的最强学习笔记:
-
出神入化——SpringCloudAlibaba.pdf
-
SpringCloud微服务架构笔记(一).pdf
-
SpringCloud微服务架构笔记(二).pdf
-
SpringCloud微服务架构笔记(三).pdf
-
SpringCloud微服务架构笔记(四).pdf
-
Dubbo框架RPC实现原理.pdf
-
Dubbo最新全面深度解读.pdf
-
Spring Boot学习教程.pdf
-
SpringBoo核心宝典.pdf
-
第一本Docker书-完整版.pdf
-
使用SpringCloud和Docker实战微服务.pdf
-
K8S(kubernetes)学习指南.pdf
另外,如果不知道从何下手开始学习呢,小编这边也有对每个微服务的核心知识点手绘了其对应的知识架构体系大纲,不过全是导出的xmind文件,全部的源文件也都在此!
《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》,点击传送门,即可获取!
ngCloud微服务架构笔记(一).pdf
-
SpringCloud微服务架构笔记(二).pdf
-
SpringCloud微服务架构笔记(三).pdf
-
SpringCloud微服务架构笔记(四).pdf
-
Dubbo框架RPC实现原理.pdf
-
Dubbo最新全面深度解读.pdf
-
Spring Boot学习教程.pdf
-
SpringBoo核心宝典.pdf
-
第一本Docker书-完整版.pdf
-
使用SpringCloud和Docker实战微服务.pdf
-
K8S(kubernetes)学习指南.pdf
[外链图片转存中…(img-6EtX2uGM-1714745692598)]
另外,如果不知道从何下手开始学习呢,小编这边也有对每个微服务的核心知识点手绘了其对应的知识架构体系大纲,不过全是导出的xmind文件,全部的源文件也都在此!
[外链图片转存中…(img-0kGSwGiZ-1714745692598)]
《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》,点击传送门,即可获取!