网络I/o编程模型24 基于netty编写RPC通信框架

本文详细介绍了如何使用Netty实现RPC通信,包括客户端和服务端的处理类、接口定义、动态代理等关键步骤。通过创建一个公共接口,消费者和提供者约定交互方式,然后利用Netty进行网络通信,实现远程过程调用。文中还展示了客户端的线程同步机制,确保调用的正确执行顺序。

一 RPC协议

1.1 RPC协议

RPC:remote  procedure  call : 远程过程调用,是一个计算机通信协议。允许一台机器程序调用另外一台机器的应用。用户无需关心细节,调用本地方法一样的调用远程方法。

常见的RPC框架:阿里的dubbo,google的gRPC, 还有apache的thrift,spring的spring cloud

二 通过基于netty实现RPC通信

2.1 需求说明

消费者和提供者约定接口和协议,消费者远程调用提供者的服务,提供者返回一个字符串,消费者打印提供者返回的数据。

1.创建一个接口,定义抽象方法,用于消费者和提供者之间的约定。

2.创建一个提供者,该类需要监听消费者的请求,并按照约定返回数据。

3.创建一个消费者,该类需要透明的调用自己不存在的方法,内部需要使用netty请求提供者返回数据。

 

 2.2 代码实现

代码说明:

1.客户端中handler的里方法执行顺序

 2.    public synchronized Object call() 和

public synchronized void channelRead(ChannelHandlerContext ctx,Object msg)

两个方法是互斥的方法:具有先后执行顺序,加了同步锁,call方法执行wait内容之前的内容的,将消息发送给服务端,服务端将信息发给客户端的channelRead()方法,执行里面notify方法将call方法后面的wait内容唤醒,继续将call方法内容执行完。

3.其中客户端使用了动态代理,目前知识技能有限,不是完全理解,待学习!!!!

2.2.1 公共接口

 1.接口

public interface NiHaoService {
    //这个接口,提供者和消费者公用一个接口
    public String hello(String mess);
}

2.实现层

package com.ljf.netty.netty.rpc;

/**
 * @ClassName: NiHaoServiceImpl
 * @Description: TODO
 * @Author: liujianfu
 * @Date: 2022/07/16 10:28:06
 * @Version: V1.0
 **/
public class NiHaoServiceImpl implements NiHaoService {
    private  static int count=0;
    //当有消费者调用该方法时,就返回一个结果
    @Override
    public String hello(String mess) {
        System.out.println("收到客户端消息:"+mess);
        //根据mess返回不同的结果
        if(mess!=null){
            return "你好客户端,我已经收到你的消息[ "+mess+" ] 第"+(++count)+"次";

        }
        else{
            return "你好客户端,我已经收到你的消息";
        }

    }
}

2.2.2 客户端

1.处理类

package com.ljf.netty.netty.rpc;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

/**
 * @ClassName: NettyClientHandler
 * @Description: TODO
 * @Author: liujianfu
 * @Date: 2022/07/16 20:28:51
 * @Version: V1.0
 **/
public class NettyClientHandler extends ChannelInboundHandlerAdapter implements Callable {
    private ChannelHandlerContext context;//上下文
    private String result;//返回结果
    private String para;//客户端调用方法时,传入的参数
    //与服务器的连接创建后,就会被调用,这个方法的第一个被调用 调用顺序   第2步
    public void channelActive(ChannelHandlerContext ctx)throws Exception{
        System.out.println("我是第2步:channelActive 被调用");
        context=ctx;//因为我们在其他方法会使用到ctx
    }
    //收到服务器的数据后,调用方法; 调用顺序,第4步
    public synchronized  void channelRead(ChannelHandlerContext ctx,Object msg) throws Exception{
        System.out.println("我是第4步 channelRead 被调用");
        result=msg.toString();
        notify();//唤醒等待的线程。
    }
    //被代理对象调用,发送数据给服务器, wait,等待被唤醒,返回结果,    调用第3步  或者第5步
    public synchronized Object call() throws Exception {
       System.out.println("我是第3步 call 被调用");
       context.writeAndFlush(para);
       //进行wait
        wait();//等待channelRead方法获取到服务器的结果后,唤醒
        System.out.println("我是第5步 call2 被调用.....");
        return result;//服务方返回结果
    }
    //调用顺序   第1步
    void  setPara(String param){
        System.out.println("我是第1步,setParam  ");
        this.para=param;
    }
    // 异常处理
    public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause) throws Exception{
        ctx.close();
    }
}

2.客户类

package com.ljf.netty.netty.rpc;

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.NioEventLoop;
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;

/**
 * @ClassName: NettyClient
 * @Description: TODO
 * @Author: liujianfu
 * @Date: 2022/07/16 15:18:51
 * @Version: V1.0
 **/
public class NettyClient {
     //创建线程池
    private static ExecutorService executorService= Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    private static NettyClientHandler client;
    private int count=0;
    //编写方法使用代理模式,获取一个代理对象
    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) {
                initClient();
            }
            client.setPara(providerName+args[0]);
            return executorService.submit(client).get();
        });
    }
    //初始化客户端
    public static void initClient(){
        client=new NettyClientHandler();
        //创建EventLoopGroup
        NioEventLoopGroup group=new NioEventLoopGroup();
        Bootstrap bootstrap=new Bootstrap();
        bootstrap.group(group);
        bootstrap.channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    public void initChannel(SocketChannel ch){
                        ChannelPipeline pipeline=ch.pipeline();
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(client);
                    }
                });
        try{
            bootstrap.connect("127.0.0.1",7000).sync();
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
}

3.启动类

package com.ljf.netty.netty.rpc;

/**
 * @ClassName: RpcClient
 * @Description: TODO
 * @Author: liujianfu
 * @Date: 2022/07/16 20:20:15
 * @Version: V1.0
 **/
public class RpcClient {
    //这里定义协议头
    public static final String proviName="oc-md#";
    public  static void main(String args[])throws  Exception{
        //创建一个消费者
        NettyClient customer=new NettyClient();
        //创建代理对象
        NiHaoService service=(NiHaoService) customer.getBean(NiHaoService.class,proviName);
        for(;;){
            Thread.sleep(2*1000);
            //通过dialing对象调用服务提供者的方法
            String res=service.hello("你好,北京");
            System.out.println("调用的结果:"+res);
        }

    }
}

2.2.3  服务端

1.处理类

package com.ljf.netty.netty.rpc;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @ClassName: NettyServerHandler
 * @Description: TODO
 * @Author: liujianfu
 * @Date: 2022/07/16 12:53:01
 * @Version: V1.0
 **/
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    //
    public void channelRead(ChannelHandlerContext ctx,Object msg)throws  Exception{
        //获取客户端发送的消息,并调用服务
        System.out.println("msg="+msg);
        //客户端在调用服务器的api时,我们需要定义一个协议
        //比如我们要求,每次发送消息都必须是以某个字符串开头,“boc-md#123”
        if(msg.toString().startsWith(RpcClient.proviName)){
            String result=new NiHaoServiceImpl().hello(msg.toString().substring(msg.toString().lastIndexOf("#")+1));
            ctx.writeAndFlush(result);
        }
    }
    public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause) throws Exception{
        ctx.close();
    }

}

2. 服务端

package com.ljf.netty.netty.rpc;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
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;

/**
 * @ClassName: NettyServer
 * @Description: TODO
 * @Author: liujianfu
 * @Date: 2022/07/16 12:23:55
 * @Version: V1.0
 **/
public class NettyServer {

    public static void startServer(String hostName,int port) {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.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();
            workerGroup.shutdownGracefully();
        }
        }
}

3.启动类

package com.ljf.netty.netty.rpc;

/**
 * @ClassName: RpcServer
 * @Description: TODO
 * @Author: liujianfu
 * @Date: 2022/07/16 12:23:05
 * @Version: V1.0
 **/
public class RpcServer {
    public static void main(String[] args) {
        NettyServer.startServer("127.0.0.1",7000);
    }
}

2.2.4.调试

客户端信息

 2.服务端信息

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值