thrift使用

thrift使用

一、簡介

thrift是一種RPC框架的實現,它的特點是可以跨語言的,如可以在java、php間進行服務註冊及調用。

二、創建thrift服務

創建thrift服務步驟如下:

  1. 定義服務(採用IDL,不針對具體語言);

  2. 生成步驟1服務需實現的接口(對應於具體語言);

  3. 對步驟2的接口進行實現;

  4. 生成服務的參數,包括以下幾點:

    • 定義服務的地址和端口號,如TNonblockingServerSocket;
    • 定義服務的處理器,也就是步驟3的實現類,如TProcessor;
    • 定義服務的序列化方式,如TBinaryProtocol;
    • 定義服務的傳輸方式,如TFramedTransport;
  5. 生成服務器, 如TNonblockingServer;

  6. 啓動服務;

總結一下,其實就兩方面的東西,第一個是定義具體的服務實現,第二個是提供服務的配置並啓動服務。

三、調用thrift服務

調用thrift服務步驟如下:

  1. 定義請求服務的地址和端口號,如TSocket;
  2. 定義服務的序列化方式,如TBinaryProtocol;
  3. 定義服務的傳輸方式,如TFramedTransport;
  4. 定義服務的客戶端,也就是服務的接口;
  5. 打開客戶端並進行服務(方法)調用;

總結一下,其實也就是服務相關的配置,接着便可進行服務的調用。

四、實例

4.1 添加maven依賴

<dependency>
    <groupId>org.apache.thrift</groupId>
    <artifactId>libthrift</artifactId>
    <version>0.10.0</version>
</dependency>

4.2 定義服務MathService.thrift

namespace java com.dragon.thriftStudy.service

service MathService {
    i32 add(1:i32 a,2:i32 b)
}

4.3 生成服務的需實現的接口MathService.java

先下載服務接口生成工具,下載地址:http://mirror.bit.edu.cn/apache/thrift/0.10.0/thrift-0.10.0.exe
接着命令生成接口:

thrift.exe -r -gen java MathService.thrift

4.4 實現步驟2生成的接口,MathService.Iface

public class MathServiceImpl implements MathService.Iface {

    public int add(int a, int b) {
        return a+b;
    }

4.5 啓動服務

public class ThriftServerMain {
    public static void main(String[] args) throws Exception {
        TNonblockingServerSocket serverSocket = new TNonblockingServerSocket(20001);
        TProcessor processor = new MathService.Processor<>(new MathServiceImpl());
        TNonblockingServer.Args arg = new TNonblockingServer.Args(serverSocket);
        arg.protocolFactory(new TBinaryProtocol.Factory());
        arg.transportFactory(new TFramedTransport.Factory());
        arg.processorFactory(new TProcessorFactory(processor));
        TNonblockingServer server = new TNonblockingServer(arg);

        server.serve();
    }
}

4.6、調用服務

public class ThriftClientMain {
    public static void main(String[] args) throws TException {
        TSocket socket = new TSocket("127.0.0.1",20001,5000);
        TTransport transport = new TFramedTransport(socket);
        TProtocol protocol = new TBinaryProtocol(transport);
        MathService.Client client = new MathService.Client(protocol);
        transport.open();

        int result = client.add(1,3);
        System.out.println("result : " +result);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章