Netty實現遠程調用RPC功能

来源:https://www.cnblogs.com/lyze/archive/2019/11/06/11803073.html
-Advertisement-
Play Games

添加依賴 <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.2.Final</version> </dependency> <dependency> <groupId>or ...


添加依賴

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.2.Final</version>
</dependency>

<dependency>
    <groupId>org.reflections</groupId>
    <artifactId>reflections</artifactId>
    <version>0.9.10</version>
</dependency>

組織架構

服務端

封裝類信息

public class ClassInfo implements Serializable {

    private static final long serialVersionUID = 1L;

    private String className;  //類名
    private String methodName;//方法名
    private Class<?>[] types; //參數類型
    private Object[] objects;//參數列表

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public String getMethodName() {
        return methodName;
    }

    public void setMethodName(String methodName) {
        this.methodName = methodName;
    }

    public Class<?>[] getTypes() {
        return types;
    }

    public void setTypes(Class<?>[] types) {
        this.types = types;
    }

    public Object[] getObjects() {
        return objects;
    }

    public void setObjects(Object[] objects) {
        this.objects = objects;
    }
}

服務端網路處理伺服器

public class NettyRPCServer {
    private int port;
    public NettyRPCServer(int port) {
        this.port = port;
    }

    public void start() {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .localAddress(port).childHandler(
                            new ChannelInitializer<SocketChannel>() {
                                @Override
                                protected void initChannel(SocketChannel ch) throws Exception {
                                    ChannelPipeline pipeline = ch.pipeline();
                                    //編碼器
                                    pipeline.addLast("encoder", new ObjectEncoder());
                                    //解碼器
                                    pipeline.addLast("decoder", new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)));
                                    //伺服器端業務處理類
                                    pipeline.addLast(new InvokeHandler());
                                }
                            });
            ChannelFuture future = serverBootstrap.bind(port).sync();
            System.out.println("......server is ready......");
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        new NettyRPCServer(9999).start();
    }
}

伺服器端業務處理類

public class InvokeHandler extends ChannelInboundHandlerAdapter {
    //得到某介面下某個實現類的名字
    private String getImplClassName(ClassInfo classInfo) throws Exception{
        //服務方介面和實現類所在的包路徑
        String interfacePath="com.lyz.server";
        int lastDot = classInfo.getClassName().lastIndexOf(".");
        String interfaceName=classInfo.getClassName().substring(lastDot);
        Class superClass=Class.forName(interfacePath+interfaceName);
        Reflections reflections = new Reflections(interfacePath);
        //得到某介面下的所有實現類
        Set<Class> ImplClassSet=reflections.getSubTypesOf(superClass);
        if(ImplClassSet.size()==0){
            System.out.println("未找到實現類");
            return null;
        }else if(ImplClassSet.size()>1){
            System.out.println("找到多個實現類,未明確使用哪一個");
            return null;
        }else {
            //把集合轉換為數組
            Class[] classes=ImplClassSet.toArray(new Class[0]);
            return classes[0].getName(); //得到實現類的名字
        }
    }

    @Override  //讀取客戶端發來的數據並通過反射調用實現類的方法
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ClassInfo classInfo = (ClassInfo) msg;
        System.out.println(classInfo);
        Object clazz = Class.forName(getImplClassName(classInfo)).newInstance();
        Method method = clazz.getClass().getMethod(classInfo.getMethodName(), classInfo.getTypes());
        //通過反射調用實現類的方法
        Object result = method.invoke(clazz, classInfo.getObjects());
        ctx.writeAndFlush(result);
    }
}

服務端介面及實現類

// 無參介面
public interface HelloNetty {
    String hello();
}

// 實現類
public class HelloNettyImpl implements HelloNetty {
    @Override
    public String hello() {
        return "hello,netty";
    }
}

// 帶參介面
public interface HelloRPC {
    String hello(String name);
}

// 實現類
public class HelloRPCImpl implements HelloRPC {
    @Override
    public String hello(String name) {
        return "hello," + name;
    }
}

客戶端

代理類

public class NettyRPCProxy {
    //根據介面創建代理對象
    public static Object create(Class target) {
        return Proxy.newProxyInstance(target.getClassLoader(), new Class[]{target}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args)
                    throws Throwable {
                //封裝ClassInfo
                ClassInfo classInfo = new ClassInfo();
                classInfo.setClassName(target.getName());
                classInfo.setMethodName(method.getName());
                classInfo.setObjects(args);
                classInfo.setTypes(method.getParameterTypes());

                //開始用Netty發送數據
                EventLoopGroup group = new NioEventLoopGroup();
                ResultHandler resultHandler = new ResultHandler();
                try {
                    Bootstrap b = new Bootstrap();
                    b.group(group)
                            .channel(NioSocketChannel.class)
                            .handler(new ChannelInitializer<SocketChannel>() {
                                @Override
                                public void initChannel(SocketChannel ch) throws Exception {
                                    ChannelPipeline pipeline = ch.pipeline();
                                    //編碼器
                                    pipeline.addLast("encoder", new ObjectEncoder());
                                    //解碼器  構造方法第一個參數設置二進位數據的最大位元組數  第二個參數設置具體使用哪個類解析器
                                    pipeline.addLast("decoder", new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)));
                                    //客戶端業務處理類
                                    pipeline.addLast("handler", resultHandler);
                                }
                            });
                    ChannelFuture future = b.connect("127.0.0.1", 9999).sync();
                    future.channel().writeAndFlush(classInfo).sync();
                    future.channel().closeFuture().sync();
                } finally {
                    group.shutdownGracefully();
                }
                return resultHandler.getResponse();
            }
        });
    }
}

客戶端業務處理類

public class ResultHandler extends ChannelInboundHandlerAdapter {

    private Object response;
    public Object getResponse() {
        return response;
    }

    @Override //讀取伺服器端返回的數據(遠程調用的結果)
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        response = msg;
        ctx.close();
    }
}

客戶端介面

// 無參介面
public interface HelloNetty {
    String hello();
}

// 帶參介面
public interface HelloRPC {
    String hello(String name);
}

測試類 服務調用方

public class TestNettyRPC {
    public static void main(String [] args){

        //第1次遠程調用
        HelloNetty helloNetty=(HelloNetty) NettyRPCProxy.create(HelloNetty.class);
        System.out.println(helloNetty.hello());

        //第2次遠程調用
        HelloRPC helloRPC =  (HelloRPC) NettyRPCProxy.create(HelloRPC.class);
        System.out.println(helloRPC.hello("RPC"));

    }
}

輸出結果

服務端

......server is ready......
com.lyz.serverStub.ClassInfo@2b894733
com.lyz.serverStub.ClassInfo@167bfa9

客戶端

hello,netty
hello,RPC

下一篇通過netty實現線上聊天功能



您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • l - Length changing 改變每頁顯示多少條數據的控制項 f - Filtering input 即時搜索框控制項 t - The Table 表格本身 i - Information 表格相關信息控制項 p - Pagination 分頁控制項 r - pRocessing 載入等待顯示信息 ...
  • 先貼上代碼 子組件代碼 1 //子組件請求介面,用自己封裝的axios 2 getupdate(){ 3 this.$post({ 4 url:this.$apis.unitupdate, 5 postType:'json' 6 }) 7 .then( () => { 8 this.$emit("g ...
  • 1、除了預設的8080埠以外,我們嘗試應用9090埠進行功能變數名稱訪問,打開server.xml 如圖: 2、在代碼裡面進行添加如下9090下麵的代碼: 如圖: 3、用9090埠進行訪問 如圖: 4、配置gzip,同樣在server.xml文件中進行設置,添加代碼 如圖: ...
  • 前言 這是我個人 面試系列 的第二篇文章,在第一篇文章中我主要分享了一下我之前面試大廠的部分面試題,很高興得到了許多前端小伙伴兒的支持和點贊。平心而論,我的學歷和背景並不是很突出,只能算普通,但幸運的是還是有機會接收到某些大廠( 比如攜程、嗶哩嗶哩、流利說、喜馬拉雅等 )的面試邀請,當然也不排除公司 ...
  • jQuery的DOM操作模塊封裝了DOM模型的insertBefore()、appendChild()、removeChild()、cloneNode()、replaceChild()等原生方法。分為5個子模塊來實現:插入元素、刪除元素、複製元素、替換元素和包裹元素,本節講解第一個子模塊:插入元素 ...
  • <el-date-picker v-model="firstdate" :picker-options="pickerOptions0" type="daterange" range-separator="至" start-placeholder="開始時間" end-placeholder="結束 ...
  • 解決方案; picker和Select組件是通過input標簽綁定,可以先通過input的父級元素移除input標簽,重新插入input標簽,最後重新初始化picker或Select組件。 <div class="weui-cell"> <div class="weui-cell__hd"><lab ...
  • 場景 Ubuntu Server 16.04 LTS上怎樣安裝下載安裝Nginx並啟動: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/102828075 Nginx的配置文件位置以及組成部分結構講解: https://blog. ...
一周排行
    -Advertisement-
    Play Games
  • Dapr Outbox 是1.12中的功能。 本文只介紹Dapr Outbox 執行流程,Dapr Outbox基本用法請閱讀官方文檔 。本文中appID=order-processor,topic=orders 本文前提知識:熟悉Dapr狀態管理、Dapr發佈訂閱和Outbox 模式。 Outbo ...
  • 引言 在前幾章我們深度講解了單元測試和集成測試的基礎知識,這一章我們來講解一下代碼覆蓋率,代碼覆蓋率是單元測試運行的度量值,覆蓋率通常以百分比表示,用於衡量代碼被測試覆蓋的程度,幫助開發人員評估測試用例的質量和代碼的健壯性。常見的覆蓋率包括語句覆蓋率(Line Coverage)、分支覆蓋率(Bra ...
  • 前言 本文介紹瞭如何使用S7.NET庫實現對西門子PLC DB塊數據的讀寫,記錄了使用電腦模擬,模擬PLC,自至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1.Windows環境下鏈路層網路訪問的行業標準工具(WinPcap_4_1_3.exe)下載鏈接:http ...
  • 從依賴倒置原則(Dependency Inversion Principle, DIP)到控制反轉(Inversion of Control, IoC)再到依賴註入(Dependency Injection, DI)的演進過程,我們可以理解為一種逐步抽象和解耦的設計思想。這種思想在C#等面向對象的編 ...
  • 關於Python中的私有屬性和私有方法 Python對於類的成員沒有嚴格的訪問控制限制,這與其他面相對對象語言有區別。關於私有屬性和私有方法,有如下要點: 1、通常我們約定,兩個下劃線開頭的屬性是私有的(private)。其他為公共的(public); 2、類內部可以訪問私有屬性(方法); 3、類外 ...
  • C++ 訪問說明符 訪問說明符是 C++ 中控制類成員(屬性和方法)可訪問性的關鍵字。它們用於封裝類數據並保護其免受意外修改或濫用。 三種訪問說明符: public:允許從類外部的任何地方訪問成員。 private:僅允許在類內部訪問成員。 protected:允許在類內部及其派生類中訪問成員。 示 ...
  • 寫這個隨筆說一下C++的static_cast和dynamic_cast用在子類與父類的指針轉換時的一些事宜。首先,【static_cast,dynamic_cast】【父類指針,子類指針】,兩兩一組,共有4種組合:用 static_cast 父類轉子類、用 static_cast 子類轉父類、使用 ...
  • /******************************************************************************************************** * * * 設計雙向鏈表的介面 * * * * Copyright (c) 2023-2 ...
  • 相信接觸過spring做開發的小伙伴們一定使用過@ComponentScan註解 @ComponentScan("com.wangm.lifecycle") public class AppConfig { } @ComponentScan指定basePackage,將包下的類按照一定規則註冊成Be ...
  • 操作系統 :CentOS 7.6_x64 opensips版本: 2.4.9 python版本:2.7.5 python作為腳本語言,使用起來很方便,查了下opensips的文檔,支持使用python腳本寫邏輯代碼。今天整理下CentOS7環境下opensips2.4.9的python模塊筆記及使用 ...