Thrift小試牛刀——在Windows中通過Thrift實現簡單服務

成功的秘訣,在永不改變既定的目的。 —— 盧梭

Thrift簡介

The Apache Thrift software framework, for scalable cross-language services development, combines a software stack with a code generation engine to build services that work efficiently and seamlessly between C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, OCaml and Delphi and other languages.

通過官方介紹,我們可以了解到Thrift是一個軟件框架,可以提供跨語言的服務開發。Thrift框架包含一個軟件棧,包含生成各種語言的引擎,我們通過Thrift提供的接口定義語言(IDL)來定義接口,然后引擎會自動生成各種語言的代碼。


Thrift架構圖.jpg

Windows平臺下Thrift安裝與使用

下載與安裝

下載文件.png

下載地址:點我下載Thrift

建議:修改名稱為Thrift.exe,方便使用

建議:配置環境變量
在系統變量Path中添加Thrift路徑到環境變量中

win10添加環境變量.png

使用

定義helloServer.thrift文件
在本例中,定義了一個用戶對象User,包含兩個字段,用戶姓名username,用戶年齡age,定義了一個接口sayHello(User user),返回用戶姓名和年齡。

namespace java cn.ac.ict.software.thrift

struct User {
        1: string username,
        2: i32 age,
    }

service HelloWorldService {
    
    string sayHello(1:User user)
}

定義完成helloServer.thrift文件之后我們使用命令thrift -r --gen java helloServer.thrift生成代碼,如下圖所示。

生成文件.png

可以看到生成的代碼包含兩個類,HelloWorldService.java和User.java類,如下圖所示。

引擎自動生成代碼.png

隨后,把自動生成的代碼添加到項目中去,如下圖所示。

將自動生成代碼添加到項目中.png

添加完代碼發現build會報錯,查看日志發現是因為沒有添加Thrift依賴的庫文件,我使用的是gradle來開發,添加Thrift的依賴就可以了,在build.gradlezhong 添加如下代碼

 // https://mvnrepository.com/artifact/org.apache.thrift/libthrift
 compile group: 'org.apache.thrift', name: 'libthrift', version: '0.10.0'

如果你使用的是mawen來添加依賴的話,可以添加如下代碼

<!-- https://mvnrepository.com/artifact/org.apache.thrift/libthrift -->
<dependency>
    <groupId>org.apache.thrift</groupId>
    <artifactId>libthrift</artifactId>
    <version>0.10.0</version>
</dependency>

更多的添加方式,大家可以參考http://mvnrepository.com/artifact/org.apache.thrift/libthrift

客戶端代碼
客戶端主要是將User對象發送給服務端,首先,實例化TTransport ,設置IP地址、服務端口port、超時時間timeout等。然后設置協議TProtocol ,注意要和服務端保持一致。接著調用接口sayHello把User對象傳遞過去。

public class HelloClient {

    private static final String SERVER_IP = "localhost";
    private static final int SERVER_PORT = 8090;
    private static final int TIMEOUT = 30000;

    public void startClient() {
        TTransport transport = null;
        try {
            transport = new TSocket(SERVER_IP, SERVER_PORT, TIMEOUT);
            // 協議要和服務端一致
            TProtocol protocol = new TBinaryProtocol(transport);
            // TProtocol protocol = new TCompactProtocol(transport);
            // TProtocol protocol = new TJSONProtocol(transport);
            HelloWorldService.Client client = new HelloWorldService.Client(protocol);
            transport.open();
            User user = new User();
            user.username = "haiker";
            user.age = 26;
            String result = client.sayHello(user);
            System.out.println("Thrify client result =: " + result);
        } catch (TException e) {
            e.printStackTrace();
        } finally {
            if (null != transport) {
                transport.close();
            }
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        HelloClient client = new HelloClient();
        client.startClient();

    }
}

HelloWorldImpl代碼
HelloWorldImpl代碼implents定義的接口sayHello,本例中只是簡單的把姓名和年齡返回。

public class HelloWorldImpl implements HelloWorldService.Iface{
    @Override
    public String sayHello(User user) throws TException {
        return "Hi,My name is " + user.username + " and My age is " + user.age;
    }

}

服務端代碼
服務端代碼首先要實例化TProcessor,傳入我們具體的HelloWorldImpl類,本例中我們使用簡單的單線程服務模型TSimpleServer來開啟一個服務。

public class HelloServer {
    private static final int SERVER_PORT = 8090;

    public void startServer() {
        try {
            System.out.println("HelloWorld TSimpleServer start ....");

            TProcessor tprocessor = new HelloWorldService.Processor<>(new HelloWorldImpl()); 

            // 簡單的單線程服務模型,一般用于測試
            TServerSocket serverTransport = new TServerSocket(SERVER_PORT);
            TServer.Args tArgs = new TServer.Args(serverTransport);
            tArgs.processor(tprocessor);
            tArgs.protocolFactory(new TBinaryProtocol.Factory());
            TServer server = new TSimpleServer(tArgs);
            server.serve();

        } catch (Exception e) {
            System.out.println("Server start error!!!");
            e.printStackTrace();
        }
    }


    /**
     * @param args
     */
    public static void main(String[] args) {
        HelloServer server = new HelloServer();
        server.startServer();
    }
}

總結

本文主要探討了Thrift在Windows中的安裝和簡單使用,以后會繼續深入探討Thrift在Linux中的安裝與使用、Thrift的原理等。

源碼地址

https://github.com/haiker2011/ThriftDemo

參考文獻

  1. http://thrift.apache.org/
  2. https://github.com/apache/thrift/
  3. http://dengqsintyt.iteye.com/blog/2005307
  4. http://www.cnblogs.com/cyfonly/p/6059374.html
  5. http://shiyanjun.cn/archives/107.html
  6. http://www.micmiu.com/soa/rpc/thrift-sample/
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容