基本介绍:
- RPC(Remote Procedure Call) : 远程过程调用,是一个计算机通讯协议,改协议允许运行于一台计算机的程序调用另一台计算机的子程序,而程序员无需额外地为这个交互作用编程
- 两个或多个应用程序都分部在不同的服务器上,它们之间的调用都像是本地方法调用一样
RPC 远程调用过程:

实例代码:
HelloService:
/**
* 这是接口,是服务提供方 和 服务消费方 都需要
*/
public interface HelloService {
String hello(String msg);
}
HelloServiceImpl:
public class HelloServiceImpl implements HelloService {
// 非共用
// private int count = 0;
// 共用
private static int count = 0;
/**
* 当有消费方 调用该方法时,就返回一个结果
* @param msg
* @return
*/
@Override
public String hello(String msg) {
System.out.println("收到客户端消息:" + msg);
// 根据 Msg 返回不同的结果
if (msg != null) {
return "您好客户端,我已经收到您的消息 [" + msg + "] 第" + (++count) + "次";
} else {
return "您好客户端,我已经收到您的消息";
}
}
}
NettyServerHandler:
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 获取客户端发送的消息, 并调用服务
System.out.println("msg = " + msg);
// 客户端在调用服务器的 api 时,必须定义一个协议 - 每次发消息时必须以某个字符串开头 "HelloService#hello#你好"
if (msg.toString().startsWith("HelloService#hello#")) {
String result = new HelloServiceImpl().hello(msg.toString().substring(msg.toString().lastIndexOf("#") + 1));
ctx.writeAndFlush(result);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}
NettyServer:
public class NettyServer {
public static void startServer(String hostname, int port) {
startServer0(hostname,port);
}
/**
* 完成 NettyServer 的初始化工作 和 启动
*/
private static void startServer0(String hostname, int port) {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workGroup)
.channel(NioServerSocketChannel.class)
.childHandler(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(new NettyServerHandler()); // 业务处理器
}
});
ChannelFuture channelFuture = serverBootstrap.bind(hostname, port).sync();
System.out.println("服务提供方开始提供服务~~");
channelFuture.channel().closeFuture().sync();
}catch (Exception e){
e.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
}
NettyClientHandler:
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.util.concurrent.Callable;
public class NettyClientHandler extends ChannelInboundHandlerAdapter implements Callable {
private ChannelHandlerContext context; // 上下文
private String result; // 返回的结果
private String param; // 客户端调用方法时,传入的参数
/**
* 与服务器的连接创建后,就会被调用
* @param ctx
* @throws Exception
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("channelActive 被调用");
context = ctx;
}
/**
* 收到服务器的数据后, 调用
* @param ctx
* @param msg
* @throws Exception
*/
@Override
public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("channelRead 被调用");
result = msg.toString();
// 唤醒等待的线程
notify();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
/**
* 被代理对象调用,发送数据给服务器 等待被唤醒(channelRead)
* @return
* @throws Exception
*/
@Override
public synchronized Object call() throws Exception {
System.out.println("call1 被调用");
context.writeAndFlush(param);
// 等待 channelRead 方法获取到服务器的结果后,唤醒
wait();
System.out.println("call2 被调用");
return result;
}
void setParam(String param) {
System.out.println("setParam 被调用");
this.param = param;
}
}
NettyClient:
public class NettyClient {
private int count = 0;
// 创建线程池
private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
private static NettyClientHandler client;
/**
* 编写方法使用代理模式,获取一个代理对象
* @param serviceClass 代理类
* @param providerName 协议头
* @return
*/
public Object getBean(final Class<?> serviceClass, final String providerName) {
return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass}, (proxy, method, args) -> {
System.out.println("(proxy, method, args) 进入..." + (++count) + "次");
if (client == null) {
intiClient();
}
// 设置要发给服务器端的信息
client.setParam(providerName + args[0]);
// 将 handler 放入线程池 并返回结果
return executor.submit(client).get();
});
}
// 初始化客户端
private static void intiClient() {
client = new NettyClientHandler();
// 创建 EventLoopGroup
NioEventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.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(client);
}
});
try {
bootstrap.connect("127.0.0.1", 9527).sync();
}catch (Exception e) {
e.printStackTrace();;
}
}
}
ClientBootstrap:
public class ClientBootstrap {
// 协议头
public static final String providerName = "HelloService#hello#";
public static void main(String[] args) throws InterruptedException {
// 创建一个消费者
NettyClient customer = new NettyClient();
// 创建代理对象
HelloService service = (HelloService) customer.getBean(HelloService.class, providerName);
for (;;) {
Thread.sleep(10 * 1000);
// 通过代理对象调用服务提供者的方法
String res = service.hello("您好 Netty~");
System.out.println("调用的结果 res: " + res);
}
}
}
ServerBootstrap:
// ServerBootstrap 会启动一个服务提供者,即 NettyServer
public class ServerBootstrap {
public static void main(String[] args) {
// TODO
NettyServer.startServer("127.0.0.1", 9527);
}
}

本文介绍了RPC的基本概念,它允许程序调用远程计算机的子程序,仿佛是本地调用。文章通过一个Netty服务器和客户端的示例,展示了如何实现RPC通信,包括HelloService接口、HelloServiceImpl服务实现、NettyServer和NettyClient的处理类,以及客户端和服务器端的交互过程。
419

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



