Thrift是一個(gè)輕量級(jí)、跨語(yǔ)言的遠(yuǎn)程服務(wù)調(diào)用框架,最初由Facebook開發(fā),后面進(jìn)入Apache開源項(xiàng)目。它通過自身的IDL中間語(yǔ)言, 并借助代碼生成引擎生成各種主流語(yǔ)言的RPC服務(wù)端/客戶端模板代碼。
Thrift支持多種不同的編程語(yǔ)言,包括C++、Java、Python、PHP、Ruby等,本系列主要講述基于Java語(yǔ)言的Thrift的配置方式和具體使用。
Thrift的技術(shù)棧
Thrift對(duì)軟件棧的定義非常的清晰, 使得各個(gè)組件能夠松散的耦合, 針對(duì)不同的應(yīng)用場(chǎng)景, 選擇不同是方式去搭建服務(wù)。
Thrift軟件棧分層從下向上分別為:傳輸層(Transport Layer)、協(xié)議層(Protocol Layer)、處理層(Processor Layer)和服務(wù)層(Server Layer)。
Thrift的特性
(一) 開發(fā)速度快
通過編寫RPC接口Thrift IDL文件,利用編譯生成器自動(dòng)生成服務(wù)端骨架(Skeletons)和客戶端樁(Stubs)。從而省去開發(fā)者自定義和維護(hù)接口編解碼、消息傳輸、服務(wù)器多線程模型等基礎(chǔ)工作。
(二) 接口維護(hù)簡(jiǎn)單
通過維護(hù)Thrift格式的IDL(接口描述語(yǔ)言)文件(注意寫好注釋),即可作為給Client使用的接口文檔使用,也自動(dòng)生成接口代碼,始終保持代碼和文檔的一致性。且Thrift協(xié)議可靈活支持接口的可擴(kuò)展性。
(三) 學(xué)習(xí)成本低
因?yàn)槠鋪?lái)自Google Protobuf開發(fā)團(tuán)隊(duì),所以其IDL文件風(fēng)格類似Google Protobuf,且更加易讀易懂;特別是RPC服務(wù)接口的風(fēng)格就像寫一個(gè)面向?qū)ο?/strong>的Class一樣簡(jiǎn)單。
初學(xué)者只需參照:http://thrift.apache.org/,一個(gè)多小時(shí)就可以理解Thrift IDL文件的語(yǔ)法使用。
(四) 多語(yǔ)言/跨語(yǔ)言支持
Thrift支持C++、 Java、Python、PHP、Ruby、Erlang、Perl、Haskell、C#、Cocoa、JavaScript、Node.js、Smalltalk等多種語(yǔ)言,即可生成上述語(yǔ)言的服務(wù)器端和客戶端程序。
對(duì)于我們經(jīng)常使用的Java、PHP、Python、C++支持良好,雖然對(duì)iOS環(huán)境的Objective-C(Cocoa)支持稍遜,但也完全滿足我們的使用要求。
(五) 穩(wěn)定/廣泛使用
Thrift在很多開源項(xiàng)目中已經(jīng)被驗(yàn)證是穩(wěn)定和高效的,例如Cassandra、Hadoop、HBase等;國(guó)外在Facebook中有廣泛使用,國(guó)內(nèi)包括百度、美團(tuán)小米、和餓了么等公司。
Thrift的數(shù)據(jù)類型
Thrift 腳本可定義的數(shù)據(jù)類型包括以下幾種類型:
Thrift的協(xié)議
Thrift可以讓用戶選擇客戶端與服務(wù)端之間傳輸通信協(xié)議的類別,在傳輸協(xié)議上總體劃分為文本(text)和二進(jìn)制(binary)傳輸協(xié)議。為節(jié)約帶寬,提高傳輸效率,一般情況下使用二進(jìn)制類型的傳輸協(xié)議為多數(shù),有時(shí)還會(huì)使用基于文本類型的協(xié)議,這需要根據(jù)項(xiàng)目/產(chǎn)品中的實(shí)際需求。常用協(xié)議有以下幾種:
Thrift的傳輸層
常用的傳輸層有以下幾種:
Thrift的服務(wù)端類型
Thrift入門示例
(一) 編寫Thrift IDL文件
a). 下載0.10.0的Thrift IDL編譯器,下載地址:http://thrift.apache.org/docs/install。 通過編譯生成器生成.java接口的類文件。
b). 下載Windows安裝環(huán)境的.exe文件,將thrift.exe的路徑加入環(huán)境變量中。在Idea上安裝Thrift編輯插件。
c). 編寫hello.thrift的IDL文件:
service HelloWorldService {
string say(1: string username)
}
d). 使用代碼生成工具生成代碼,執(zhí)行以下命令:
thrift -gen java hello.thrift
e). 由于未指定代碼生成的目標(biāo)目錄,生成的類文件默認(rèn)存放在gen-java目錄下。這里生成一個(gè)HelloWorldService.java類文件,文件大小超過數(shù)千行,下面截取一部分核心代碼。
public class HelloWorldService {
public interface Iface {
public String say(String username) throws org.apache.thrift.TException;
}
public interface AsyncIface {
public void say(String username, org.apache.thrift.async.AsyncMethodCallback<String> resultHandler) throws org.apache.thrift.TException;
}
public static class Client extends org.apache.thrift.TServiceClient implements Iface {
public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {
public Factory() {
}
public Client getClient(org.apache.thrift.protocol.TProtocol prot) {
return new Client(prot);
}
public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
return new Client(iprot, oprot);
}
}
public Client(org.apache.thrift.protocol.TProtocol prot) {
super(prot, prot);
}
public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
super(iprot, oprot);
}
public String say(String username) throws org.apache.thrift.TException {
send_say(username);
return recv_say();
}
// 省略.....
}
public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface {
public static class Factory implements org.apache.thrift.async.TAsyncClientFactory<AsyncClient> {
private org.apache.thrift.async.TAsyncClientManager clientManager;
private org.apache.thrift.protocol.TProtocolFactory protocolFactory;
public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) {
this.clientManager=clientManager;
this.protocolFactory=protocolFactory;
}
public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) {
return new AsyncClient(protocolFactory, clientManager, transport);
}
}
public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) {
super(protocolFactory, clientManager, transport);
}
public void say(String username, org.apache.thrift.async.AsyncMethodCallback<String> resultHandler) throws org.apache.thrift.TException {
checkReady();
say_call method_call=new say_call(username, resultHandler, this, ___protocolFactory, ___transport);
this.___currentMethod=method_call;
___manager.call(method_call);
}
// 省略.....
}
// 省略.....
}
對(duì)于開發(fā)人員而言,使用原生的Thrift框架,僅需要關(guān)注以下四個(gè)核心內(nèi)部接口/類:Iface, AsyncIface, Client和AsyncClient。
(二) 新建Maven工程
a). 新建maven工程,引入thrift的依賴,這里使用的是版本0.10.0。
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>0.10.0</version>
</dependency>
b). 將生成類的HelloWorldService.java源文件拷貝進(jìn)項(xiàng)目源文件目錄中,并實(shí)現(xiàn)HelloWorldService.Iface的定義的say()方法。
HelloWorldServiceImpl.java
public class HelloWorldServiceImpl implements HelloWorldService.Iface {
@Override
public String say(String username) throws TException {
return "Hello " + username;
}
}
c). 服務(wù)器端程序編寫:
SimpleServer.java
public class SimpleServer {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket=new ServerSocket(ServerConfig.SERVER_PORT);
TServerSocket serverTransport=new TServerSocket(serverSocket);
HelloWorldService.Processor processor=
new HelloWorldService.Processor<HelloWorldService.Iface>(new HelloWorldServiceImpl());
TBinaryProtocol.Factory protocolFactory=new TBinaryProtocol.Factory();
TSimpleServer.Args tArgs=new TSimpleServer.Args(serverTransport);
tArgs.processor(processor);
tArgs.protocolFactory(protocolFactory);
// 簡(jiǎn)單的單線程服務(wù)模型 一般用于測(cè)試
TServer tServer=new TSimpleServer(tArgs);
System.out.println("Running Simple Server");
tServer.serve();
}
}
d). 客戶端程序編寫:
SimpleClient.java
public class SimpleClient {
public static void main(String[] args) {
TTransport transport=null;
try {
transport=new TSocket(ServerConfig.SERVER_IP, ServerConfig.SERVER_PORT, ServerConfig.TIMEOUT);
TProtocol protocol=new TBinaryProtocol(transport);
HelloWorldService.Client client=new HelloWorldService.Client(protocol);
transport.open();
String result=client.say("Leo");
System.out.println("Result=: " + result);
} catch (TException e) {
e.printStackTrace();
} finally {
if (null !=transport) {
transport.close();
}
}
}
}
e). 運(yùn)行服務(wù)端程序,服務(wù)端在指定端口監(jiān)聽客戶端的連接請(qǐng)求,控制臺(tái)輸出啟動(dòng)日志:
image
f). 運(yùn)行客戶端程序,客戶端通過網(wǎng)絡(luò)請(qǐng)求HelloWorldService的say()方法的具體實(shí)現(xiàn),控制臺(tái)輸出返回結(jié)果:
這里使用的一個(gè)基于單線程同步的簡(jiǎn)單服務(wù)模型,一般僅用于入門學(xué)習(xí)和測(cè)試!
本文對(duì)Thrift的概念做了相關(guān)介紹,體驗(yàn)了一番thrift程序如何編寫!
Thrift 是一款高性能、開源的 RPC 框架,產(chǎn)自 Facebook 后貢獻(xiàn)給了 Apache,Thrift 囊括了整個(gè) RPC 的上下游體系,自帶序列化編譯工具,因?yàn)?Thrift 采用的是二進(jìn)制序列化,并且與 gRPC 一樣使用的都是長(zhǎng)連接建立 client 與 server 之間的通訊,相比于比傳統(tǒng)的使用XML,JSON,SOAP等短連接的解決方案性能要快得多。
本篇只介紹 Python 關(guān)于 Thrift 的基礎(chǔ)使用。
通過 pip 命令安裝,缺點(diǎn)必須要有外網(wǎng)或者內(nèi)網(wǎng)的 pip 源:$ pip install thrift
從 github 上下載 thrift 0.10.0 的源碼,解壓后進(jìn)入:thrift-0.10.0/compiler/cpp 目錄執(zhí)行如下命令完成編譯后,將其放入到系統(tǒng)環(huán)境變量下即可使用:
$ mkdir cmake-build
$ cd cmake-build
$ cmake ..
$ make
$ thrift -version,如果打印出來(lái):Thrift version 0.10.0 表明 complier 安裝成功
下面我們使用 Thrift 定義一個(gè)接口,該接口實(shí)現(xiàn)對(duì)傳入的數(shù)據(jù)進(jìn)行大寫的格式化處理。
Paste_Image.png
client目錄下的 client.py 實(shí)現(xiàn)了客戶端用于發(fā)送數(shù)據(jù)并打印接收到 server 端處理后的數(shù)據(jù)
example.thrift:
namespace py example
struct Data {
1: string text
}
service format_data {
Data do_format(1:Data data),
}
進(jìn)入 thrift_file 目錄執(zhí)行:$ thrift -out .. --gen py example.thrift,就會(huì)在 thrift_file 的同級(jí)目錄下生成 python 的包:example
Paste_Image.png
server.py:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
__author__='xieyanke'
from example import format_data
from example import ttypes
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
__HOST='localhost'
__PORT=8080
class FormatDataHandler(object):
def do_format(self, data):
return ttypes.Data(data.text.upper())
if __name__=='__main__':
handler=FormatDataHandler()
processor=format_data.Processor(handler)
transport=TSocket.TServerSocket(__HOST, __PORT)
tfactory=TTransport.TBufferedTransportFactory()
pfactory=TBinaryProtocol.TBinaryProtocolFactory()
rpcServer=TServer.TSimpleServer(processor,transport, tfactory, pfactory)
print('Starting the rpc server at', __HOST,':', __PORT)
rpcServer.serve()
client.py:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from example.format_data import Client
from example.format_data import Data
__HOST='localhost'
__PORT=8080
tsocket=TSocket.TSocket(__HOST, __PORT)
transport=TTransport.TBufferedTransport(tsocket)
protocol=TBinaryProtocol.TBinaryProtocol(transport)
client=Client(protocol)
data=Data('hello,world!')
transport.open()
print(client.do_format(data).text)
先啟動(dòng) server,之后再執(zhí)行 client
注意
import sys
sys.path.append(r"X:\xx\thrift_demo") #thrift_demo 目錄的絕對(duì)路徑