1. 程式人生 > >RPC框架實踐之:Apache Thrift

RPC框架實踐之:Apache Thrift

接口查詢 ima 安裝 數據通信 @override onf 成功 內容 文件中

一、概述

RPC(Remote Procedure Call)即 遠程過程調用,說的這麽抽象,其實簡化理解就是一個節點如何請求另一節點所提供的服務。在文章 微服務調用鏈追蹤中心搭建 一文中模擬出來的調用鏈:ServiceA ---> ServiceB ---> ServiceC 就是一個遠程調用的例子,只不過這篇文章裏是通過RestTemplate這種 同步調用方式,利用的是HTTP協議在應用層完成的,這種方法雖然奏效,但有時效率並不高。而RPC可以不依賴於應用層協議,可以直接基於TCP進行遠程調用,在傳輸層中即可完成通信,因此更適於某些對效率要求更高的場景。由於RPC調用方式依賴於客戶端與服務端之間建立Socket連接來實現二進制數據通信,底層會比較復雜,所以一些RPC框架應運而生來封裝這種復雜性,讓開發者將精力聚焦於業務之上。常見的RPC框架包括:Thrift、gRPC、Finagle、Dubbo等等,從本文開始作者將選一些實踐一下,本文主要記錄作者對於Thrift框架的實踐過程。

Thrift是Apache的項目,它結合了功能強大的軟件堆棧和代碼生成引擎,可以在諸多語言之間提供無縫支持。

心動不如行動吧!


二、實驗環境

  • Mac OS X 10.13.2
  • SpringBoot 2.0.1
  • Thrift 0.11.0
  • IDE:IntelliJ IDEA 2018.01

為了便於讀者理解,我先將下文內容總結一下,包含7點:

  • Thrift環境搭建
  • IDEA中Thrift插件配置
  • 創建 Thrift 項目並編譯(目的:定義RPC接口)
  • 開發Thrift API接口
  • 開發RPC服務端
  • 開發RPC客戶端
  • RPC通信實際實驗

三、Thrift環境搭建

  • 方法一: 原生安裝方式,通過官方提供的步驟一步一步來安裝

參考這裏:Mac上Thrift官方安裝教程

  • 方法二: 使用 brew 工具(推薦

brew install thrift

技術分享圖片


四、IDEA中Thrift插件配置

方法一:直接在IDEA界面中配置

打開IDEA的插件中心,搜索 Thrift 即可安裝

技術分享圖片

方法二:手動下載Thrift插件安裝

就像文章 SpringBoot優雅編碼之:Lombok加持 一文中在IDEA中安裝Lombok插件一樣,有時由於網絡原因,方法一不奏效時插件裝不上,此時可以手動下載插件並安裝。

可以去如下地址下載Thrift插件:http://plugins.jetbrains.com/plugin/7331-thrift-support

技術分享圖片

然後去IDEA中 Install plugin from disk... 選擇下載的zip包安裝,然後重啟IDE即可

技術分享圖片

安裝完成的成功標誌是 Compiler 中出現了 Thrift編譯器!如下圖所示:

技術分享圖片


五、創建 Thrift 項目並編譯(定義RPC接口)

  • 第一步:創建Thrift項目並配置

IDE 很智能地在 New Project 時提供 Thrift項目創建選項:

技術分享圖片

項目創建完成以後,在 Project Settings 中設置好 Facets 的 Thrift配置,如下圖所示,這裏我們添加一個 Java的Generator

技術分享圖片

在彈出的對話框中配置好 Output folder 路徑,該路徑用於存放由 thrift文件 轉化而成的 java源文件

技術分享圖片

OK,Thrift項目就緒了!

  • 第二步:創建thrift接口文件

這裏創建一個thrift接口文件:RPCDateService.thrift

thrift文件的寫法我不贅述,跟gRPC一樣有其自己的語法,namespace是最後生成的接口文件的包名

namespace java com.hansonwang99.thrift.interface
service RPCDateService{
    string getDate(1:string userName)
}

在該接口文件中,我們定義了一個 提供日期的Service,讓客戶端能通過該接口查詢到服務器當前的時間

  • 第三步:編譯Thrift源文件生成Java接口類

右擊.thrift源文件,點擊 Recompile ‘xxx.thrift‘ 即可完成 thrift接口文件 ---> java接口文件 的轉換

技術分享圖片

輸出的Java接口文件生成於上文中配置的 output 中,其 包結構=上文.thrift文件中的namespace ,其包結構如下圖所示,該Java接口十分重要,後續會用於實現Client和Server之間的RPC調用。

技術分享圖片


六、開發Thrift API接口

我們創建一個Maven項目:ThriftAPI,其包含的的就是上文由自定義Thrift接口生成的Java接口:RPCDateService.java 文件,該文件將用於後面的RPC服務端和RPC客戶端的代碼實現!

  • pom.xml中添加thrift依賴
    <dependencies>
        <dependency>
            <groupId>org.apache.thrift</groupId>
            <artifactId>libthrift</artifactId>
            <version>0.11.0</version>
        </dependency>
    </dependencies>
  • 添加RPCDateService.java

將上文 第五步RPCDateService.thrift 生成的 RPCDateService.java 原樣拷貝到該Maven項目中即可,代碼結構如下:

技術分享圖片

再次強調,該 ThriftAPI項目 會服務於下文即將要創建的RPC服務端和RPC客戶端


七、開發RPC服務端

我們是利用SpringBoot來實現RPC服務端

  • pom.xml中添加依賴

這裏除了自動添加好的SpringBoot依賴外,需要額外添加的就是上文的 ThriftAPI依賴

<dependency>
        <groupId>com.hansonwang99</groupId>
        <artifactId>ThriftAPI</artifactId>
         <version>1.0-SNAPSHOT</version>
</dependency>
  • 創建Controller並實現RPC接口
@Controller
public class RPCDateServiceImpl implements RPCDateService.Iface {
    @Override
    public String getDate(String userName) throws TException {
        Date now=new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("今天是"+"yyyy年MM月dd日 E kk點mm分");
        String nowTime = simpleDateFormat.format( now );
        return "Hello " + userName + "\n" + nowTime;
    }
}

這裏將服務器當前時間以字符串形式返回給調用端!

  • 編寫RPCThriftServer:用於啟動RPC服務器
@Component
public class RPCThriftServer {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Value("${thrift.port}")
    private int port;
    @Value("${thrift.minWorkerThreads}")
    private int minThreads;
    @Value("${thrift.maxWorkerThreads}")
    private int maxThreads;

    private TBinaryProtocol.Factory protocolFactory;
    private TTransportFactory transportFactory;

    @Autowired
    private RPCDateServiceImpl rpcDateService;

    public void init() {
        protocolFactory = new TBinaryProtocol.Factory();
        transportFactory = new TTransportFactory();
    }

    public void start() {
        RPCDateService.Processor processor = new RPCDateService.Processor<RPCDateService.Iface>( rpcDateService );
        init();
        try {
            TServerTransport transport = new TServerSocket(port);
            TThreadPoolServer.Args tArgs = new TThreadPoolServer.Args(transport);
            tArgs.processor(processor);
            tArgs.protocolFactory(protocolFactory);
            tArgs.transportFactory(transportFactory);
            tArgs.minWorkerThreads(minThreads);
            tArgs.maxWorkerThreads(maxThreads);
            TServer server = new TThreadPoolServer(tArgs);
            logger.info("thrift服務啟動成功, 端口={}", port);
            server.serve();
        } catch (Exception e) {
            logger.error("thrift服務啟動失敗", e);
        }
    }
}
  • 創建SpringBootApplication
@SpringBootApplication
public class RPCThriftServerApplication {
    private static RPCThriftServer rpcThriftServer;
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(RPCThriftServerApplication.class, args);
        try {
            rpcThriftServer = context.getBean(RPCThriftServer.class);
            rpcThriftServer.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • 添加配置文件application.properties
thrift.port=6666
thrift.minWorkerThreads=10
thrift.maxWorkerThreads=100

我們讓thrift服務起在6666端口!

  • 啟動RPC服務端服務

技術分享圖片


八、開發RPC客戶端

這裏同樣用SpringBoot來實現RPC客戶端!

  • pom.xml中添加依賴

    此處同RPC服務端依賴,不贅述

  • 編寫RPCThriftClient:用於發出RPC調用

這裏包含兩個文件:RPCThriftClient.javaRPCThriftClientConfig.java

RPCThriftClient.java如下:

public class RPCThriftClient {
    private RPCDateService.Client client;
    private TBinaryProtocol protocol;
    private TSocket transport;
    private String host;
    private int port;

    public String getHost() {
        return host;
    }
    public void setHost(String host) {
        this.host = host;
    }
    public int getPort() {
        return port;
    }
    public void setPort(int port) {
        this.port = port;
    }

    public void init() {
        transport = new TSocket(host, port);
        protocol = new TBinaryProtocol(transport);
        client = new RPCDateService.Client(protocol);
    }

    public RPCDateService.Client getRPCThriftService() {
        return client;
    }

    public void open() throws TTransportException {
        transport.open();
    }

    public void close() {
        transport.close();
    }
}

RPCThriftClientConfig.java是利用config生成bean

@Configuration
public class RPCThriftClientConfig {
    @Value("${thrift.host}")
    private String host;
    @Value("${thrift.port}")
    private int port;

    @Bean(initMethod = "init")
    public RPCThriftClient rpcThriftClient() {
        RPCThriftClient rpcThriftClient = new RPCThriftClient();
        rpcThriftClient.setHost(host);
        rpcThriftClient.setPort(port);
        return rpcThriftClient;
    }
}
  • 編寫Restful的Controller作為調用入口
@RestController
@RequestMapping("/hansonwang99")
public class RPCThriftContoller {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private RPCThriftClient rpcThriftClient;

    @RequestMapping(value = "/thrift", method = RequestMethod.GET)
    public String thriftTest(HttpServletRequest request, HttpServletResponse response) {
        try {
            rpcThriftClient.open();
            return rpcThriftClient.getRPCThriftService().getDate("hansonwang99");
        } catch (Exception e) {
            logger.error("RPC調用失敗", e);
            return "error";
        } finally {
            rpcThriftClient.close();
        }
    }
}
  • 創建SpringBootApplication
@SpringBootApplication
public class RPCThriftClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(RPCThriftClientApplication.class, args);
    }
}
  • 添加配置文件application.properties
thrift.host=localhost
thrift.port=6666
server.port=9999
  • 啟動RPC客戶端服務

技術分享圖片


九、RPC通信實驗

我們瀏覽器輸入:localhost:9999/hansonwang99/thrift 即可查看客戶端從服務端取回的服務器當前時間,說明RPC通信過程打通!

技術分享圖片

RPC框架實踐之:Apache Thrift