RPC基本介绍
RPC(Remote Procedure Call) - 远程过程调用,是一个计算机通信协议,该协议允许运行于一台计算机的程序调用另一台计算机的子程序,而程序员无需额外地为这个交互作用编程。
PRC调用流程说明
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封装起来,用户无需关心这些细节,可以像调用本地方法一样完成远程服务的调用。
实现
创建一个接口定义抽象方法用于消费者和提供者之间的约定。
//这个是接口,是服务的提供方和服务的消费方都要使用的
public interface HelloService {
String hello(String mes);
}
创建一个提供者,该类需要监听消费者的请求,并按照约定返回数据。
public class NettyServer {
public static void startServer(String hostName,int port){
startServer0(hostName,port);
}
//NettyServer的初始化和启动
private static void startServer0(String hostname,int port){
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
try{
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline channelPipeline=socketChannel.pipeline();
channelPipeline.addLast(new StringEncoder());
channelPipeline.addLast(new StringDecoder());
channelPipeline.addLast(new NettyServerHandler());
}
});
ChannelFuture channelFuture = bootstrap.bind(hostname, port).sync();
System.out.println("服务提供方开始 提供服务~~");
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("出现异常="+cause.getMessage());
ctx.close();
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//获取客户端发送
System.out.println("msg="+msg);
//客户端在调用服务器的api时,需要定义一个协议
//比如我们要求每次发送消息都必须以某个字符串开头“HelloServiceHello#”
if(msg.toString().startsWith(ClientBootstrap.providerName)){
String result=new HelloServiceImpl().hello(msg.toString().substring(msg.toString().lastIndexOf("#")+1));
ctx.writeAndFlush(result);
}
}
}
public class HelloServiceImpl implements HelloService {
private static int count = 0;
//当有消费方调用该方法时, 就返回一个结果
@Override
public String hello(String mes) {
System.out.println("收到客户端消息=" + mes);
//根据mes 返回不同的结果
if(mes != null) {
return "你好客户端, 我已经收到你的消息 [" + mes + "] 第" + (++count) + " 次";
} else {
return "你好客户端, 我已经收到你的消息 ";
}
}
}
public class ServerBootstrap {
public static void main(String[] args) {
//代码代填..
NettyServer.startServer("127.0.0.1", 7000);
}
}
创建一个消费者,该类需要透明的调用自己不存在的方法,内部需要使用Netty 请求提供者返回数据
public class NettyClient {
private static ExecutorService executor= Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
private static NettyClientHandler client;
//编写方法使用代理模式,获取一个代理对象
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)进入。。。");
//{部分的代码,客户端每调用一次hello,就会进入到该代码}
if(client==null){
initClient();
}
//设置要发给服务器端的信息
//providerName 协议头 args[0] 就是客户端调用api hello(???),参数
client.setPara(providerName+args[0]);
return executor.submit(client).get();
});
}
//初始化客户端
private static void initClient(){
client=new NettyClientHandler();
//创建EventLoopGroup
NioEventLoopGroup group=new NioEventLoopGroup();
try {
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 StringEncoder());
pipeline.addLast(new StringDecoder());
pipeline.addLast(client);
}
});
bootstrap.connect("127.0.0.1", 7000).sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class NettyClientHandler extends ChannelInboundHandlerAdapter implements Callable {
private ChannelHandlerContext context;//上下文
private String result;//返回 结果
private String para;//客户端调用方法时,传入的参数
//被代理对象调用,发送数据给服务器 ->wait ->等待被唤醒()->返回结果
//(3)->(5)
@Override
public synchronized Object call() throws Exception {
System.out.println("Call方法被调用");
context.writeAndFlush(para);
wait();//等待channel Read 方法获取到服务器的结果后,唤醒
System.out.println("call2被调用");
return result;//服务方返回结果
}
//收到服务器消息后调用方法
//(4)
@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 {
System.out.println("出现异常="+cause.getMessage());
ctx.close();
}
//与服务器的连接创建后,就会被调用//(1)
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("channelActive 被调用");
context=ctx;// 因为在其他方法中会用到ctx
}
//(2)
public void setPara(String para){
this.para=para;
}
}
public class ClientBootstrap {
//这里定义协议头
public static final String providerName="HelloService#hello#";
public static void main(String[] args) {
//创建一个消费者
NettyClient customer=new NettyClient();
//创建代理对象
HelloService service=(HelloService)customer.getBean(HelloService.class,providerName);
//通过代理对象调用服务提供者的方法(服务)
String res=service.hello("你好 dubbo");
System.out.println("调用的结果 res="+res);
}
}