常见的 RPC 框架有: 比较知名的如阿里的Dubbo、google的gRPC、Go语言的rpcx、Apache的thrift, Spring 旗下的 Spring Cloud
RPC调用流程图
说明:
1) client以本地方式调用服务
2)client stub接受调用负责将方法,参数等封装成能够进行网络传输的消息体
3) client stub将消息进行编码并发送到客户端
4)server stub收到消息后进行解码
5)server stub根据解码的消息调用本地服务
6) 本地服务执行并将结果返回给server stub
7)server stub将返回的结果编码,并发送至消费方
8)client stub收到消息后进行解码
9)client得到结果
RPC的目标就是将2-8步骤封装起来,用户无需关系这些细节,用本地方法就可以完成远程服务调用。
客户端启动类
/**
* @author gusteu
* @date 2022/04/17 08:09:11
*/
public class ClientBootstrap {
public static void main(String[] args) throws InterruptedException {
NettyClient nettyClient = new NettyClient();
UserService userService = (UserService) nettyClient.getBean(UserService.class, InterfaceConstant.PROVIDER_NAME);
for (int i = 0; i < 6; i++) {
Thread.sleep(3000);
System.out.println(userService.getUserNameById("20132230310" + i));
}
}
}
客户端
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author gusteu
* @date 2022/04/17 08:11:33
*/
public class NettyClient {
private static ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
private static ClientHandler clientHandler;
/**
* 创建一个代理对象
*/
public Object getBean(final Class<?> serviceClass,
final String providerName) {
return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
new Class<?>[]{serviceClass}, (proxy, method, args) -> {
if (clientHandler == null) {
initClient();
}
// 设置参数
clientHandler.setPara(providerName + args[0]);
return executorService.submit(clientHandler).get();
});
}
private static void initClient() throws InterruptedException {
clientHandler = new ClientHandler();
NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(nioEventLoopGroup)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
pipeline.addLast(clientHandler);
}
});
bootstrap.connect("127.0.0.1", 8001).sync();
}
}
客户端处理器
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.util.concurrent.Callable;
/**
* @author gusteu
* @date 2022/04/17 08:13:31
*/
public class ClientHandler extends ChannelInboundHandlerAdapter implements Callable {
private ChannelHandlerContext context;
private String result;
private String para;
/**
* 与服务器的连接已经及建立之后将被调用
* @param ctx
*/
@Override
public void channelActive(ChannelHandlerContext ctx) {
context = ctx;
}
/**
* 收到服务端数据,唤醒等待线程
*/
@Override
public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) {
result = msg.toString();
notify();
}
/**
* 写出数据,开始等待唤醒
*/
@Override
public synchronized Object call() throws InterruptedException {
context.writeAndFlush(para);
wait();
return result;
}
void setPara(String para) {
this.para = para;
}
}
接口常量类
public class InterfaceConstant {
public static final String PROVIDER_NAME = "UserService#getUserNameById#";
}
服务端启动类
/**
* @author gusteu
* @date 2022/04/17 08:34:39
*/
public class ServerBootstrap {
public static void main(String[] args) {
NettyServer.startServer("127.0.0.1", 8001);
}
}
服务端初始化
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
/**
* @author gusteu
* @date 2022/04/17 08:29:51
*/
public class NettyServer {
/**
* 启动客户端
*/
public static void startServer(String hostName, int port) {
startServer0(hostName, port);
}
private static void startServer0(String hostName, int port) {
try {
ServerBootstrap bootstrap = new ServerBootstrap();
NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
bootstrap.group(eventLoopGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new StringDecoder());
p.addLast(new StringEncoder());
p.addLast(new ServerHandler());
}
});
bootstrap.bind(hostName, port).sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
服务端handler
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
/**
* @author gusteu
* @date 2022/04/17 08:30:46
*/
public class ServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 如何符合约定,则调用本地方法,返回数据
if (msg.toString().startsWith(InterfaceConstant.PROVIDER_NAME)) {
String result = new UserServiceImpl()
.getUserNameById(msg.toString().substring(msg.toString().lastIndexOf("#") + 1));
ctx.writeAndFlush(result);
}
}
}
业务接口和实现类
/**
* @author gusteu
* @date 2022/04/17 08:25:17
*/
public interface UserService {
String getUserNameById(String id);
}
import java.util.UUID;
/**
* @author gusteu
* @date 2022/04/17 08:32:42
*/
public class UserServiceImpl implements UserService {
@Override
public String getUserNameById(String id) {
return UUID.randomUUID().toString();
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)