這是一個建立於
的文章,其中的資訊可能已經有所發展或是發生改變。
Thrift 簡介:
Thrift 是一款高效能、開源的 RPC 架構,產自 Facebook 後貢獻給了 Apache,Thrift 囊括了整個 RPC 的上下遊體系,內建序列化編譯工具,因為 Thrift 採用的是二進位序列化,並且與 gRPC 一樣使用的都是長串連建立 client 與 server 之間的通訊,相比於比傳統的使用XML,JSON,SOAP等短串連的解決方案效能要快得多。
本篇只介紹 Golang 關於 Thrift 的基礎使用。
安裝
實踐:
下面我們使用 Thrift 定義一個介面,該介面實現對傳入的資料進行大寫的格式化處理。
- 建立 golang 項目 ThriftDemo 工程:
Paste_Image.png
- client目錄下的 client.go 實現了用戶端用於發送資料並列印接收到 server 端處理後的資料
- server 目錄下的 server.go 實現了服務端用於接收用戶端發送的資料,並對資料進行大寫處理後返回給用戶端
- thrift_file 用於存放 thrift 的 IDL 檔案: *.thrift
example.thrift:
namespace py examplestruct Data { 1: string text}service format_data { Data do_format(1:Data data),}
- 編譯 thrift 檔案
進入 thrift_file 目錄執行:$ thrift -out .. --gen go example.thrift,就會在 thrift_file 的同級目錄下產生 golang 的包:example,其中 format_data-remote 是產生的測試代碼可以不用特別關注
Paste_Image.png
package mainimport ( "ThriftDemo/example" "strings" "git.apache.org/thrift.git/lib/go/thrift" "fmt" "log")type FormatDataImpl struct {}func (fdi *FormatDataImpl) DoFormat(data *example.Data) (r *example.Data, err error){ var rData example.Data rData.Text = strings.ToUpper(data.Text) return &rData, nil}const ( HOST = "localhost" PORT = "8080")func main() { handler := &FormatDataImpl{} processor := example.NewFormatDataProcessor(handler) serverTransport, err := thrift.NewTServerSocket(HOST + ":" + PORT) if err != nil { log.Fatalln("Error:", err) } transportFactory := thrift.NewTFramedTransportFactory(thrift.NewTTransportFactory()) protocolFactory := thrift.NewTBinaryProtocolFactoryDefault() server := thrift.NewTSimpleServer4(processor, serverTransport, transportFactory, protocolFactory) fmt.Println("Running at:", HOST + ":" + PORT) server.Serve()}
package mainimport ( "git.apache.org/thrift.git/lib/go/thrift" "net" "fmt" "ThriftDemo/example" "log")const ( HOST = "localhost" PORT = "8080")func main() { tSocket, err := thrift.NewTSocket(net.JoinHostPort(HOST, PORT)) if err != nil { log.Fatalln("tSocket error:", err) } transportFactory := thrift.NewTFramedTransportFactory(thrift.NewTTransportFactory()) transport := transportFactory.GetTransport(tSocket) protocolFactory := thrift.NewTBinaryProtocolFactoryDefault() client := example.NewFormatDataClientFactory(transport, protocolFactory) if err := transport.Open(); err != nil { log.Fatalln("Error opening:", HOST + ":" + PORT) } defer transport.Close() data := example.Data{Text:"hello,world!"} d, err := client.DoFormat(&data) fmt.Println(d.Text)}
- 執行驗證結果:
- 先啟動 server,之後再執行 client
- client 側控制台如果列印的結果為: HELLO,WORLD! ,證明 Thrift 的 RPC 介面定義成功