Thrift小試牛刀——在Windows中通過Thrift實(shí)現(xiàn)簡(jiǎn)單服務(wù)

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

Thrift簡(jiǎn)介

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是一個(gè)軟件框架,可以提供跨語言的服務(wù)開發(fā)。Thrift框架包含一個(gè)軟件棧,包含生成各種語言的引擎,我們通過Thrift提供的接口定義語言(IDL)來定義接口,然后引擎會(huì)自動(dòng)生成各種語言的代碼。


Thrift架構(gòu)圖.jpg

Windows平臺(tái)下Thrift安裝與使用

下載與安裝

下載文件.png

下載地址:點(diǎn)我下載Thrift

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

建議:配置環(huán)境變量
在系統(tǒng)變量Path中添加Thrift路徑到環(huán)境變量中

win10添加環(huán)境變量.png

使用

定義helloServer.thrift文件
在本例中,定義了一個(gè)用戶對(duì)象User,包含兩個(gè)字段,用戶姓名username,用戶年齡age,定義了一個(gè)接口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

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

引擎自動(dòng)生成代碼.png

隨后,把自動(dòng)生成的代碼添加到項(xiàng)目中去,如下圖所示。

將自動(dòng)生成代碼添加到項(xiàng)目中.png

添加完代碼發(fā)現(xiàn)build會(huì)報(bào)錯(cuò),查看日志發(fā)現(xiàn)是因?yàn)闆]有添加Thrift依賴的庫文件,我使用的是gradle來開發(fā),添加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對(duì)象發(fā)送給服務(wù)端,首先,實(shí)例化TTransport ,設(shè)置IP地址、服務(wù)端口port、超時(shí)時(shí)間timeout等。然后設(shè)置協(xié)議TProtocol ,注意要和服務(wù)端保持一致。接著調(diào)用接口sayHello把User對(duì)象傳遞過去。

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);
            // 協(xié)議要和服務(wù)端一致
            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,本例中只是簡(jiǎn)單的把姓名和年齡返回。

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;
    }

}

服務(wù)端代碼
服務(wù)端代碼首先要實(shí)例化TProcessor,傳入我們具體的HelloWorldImpl類,本例中我們使用簡(jiǎn)單的單線程服務(wù)模型TSimpleServer來開啟一個(gè)服務(wù)。

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()); 

            // 簡(jiǎn)單的單線程服務(wù)模型,一般用于測(cè)試
            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();
    }
}

總結(jié)

本文主要探討了Thrift在Windows中的安裝和簡(jiǎn)單使用,以后會(huì)繼續(xù)深入探討Thrift在Linux中的安裝與使用、Thrift的原理等。

源碼地址

https://github.com/haiker2011/ThriftDemo

參考文獻(xiàn)

  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/
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容