Thrift-簡單實用

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

簡介

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.

Apache Thrift是一個軟體架構,用來進行可擴充跨語言的服務開發,結合了軟體堆棧和代碼產生引擎,用來構建C++,Java,Python...等語言,使之它們之間無縫結合、高效服務。

安裝

brew install thrift

作用

跨語言調用,打破不同語言之間的隔閡。
跨項目調用,微服務的麼麼噠。

樣本

前提

  • thrift版本:

  • Go的版本、Php版本、Python版本:

說明

該樣本包含python,php,go三種語言。(java暫無)

建立HelloThrift.thrift

  • 進入目錄
cd /Users/birjemin/Developer/Php/study-php
  • 編寫HelloThrift.thrift
vim HelloThrift.thrift

內容如下:

namespace php HelloThrift {  string SayHello(1:string username)}

Php測試

  • 載入thrift-php庫
composer require apache/thrift
  • 產生php版本的thrift相關檔案
cd /Users/birjemin/Developer/Php/study-phpthrift -r --gen php:server HelloThrift.thrift

這時目錄中產生了一個叫做gen-php的目錄。

  • 建立Server.php檔案
<?php/** * Created by PhpStorm. * User: birjemin * Date: 22/02/2018 * Time: 3:59 PM */namespace HelloThrift\php;require_once 'vendor/autoload.php';use Thrift\ClassLoader\ThriftClassLoader;use Thrift\Protocol\TBinaryProtocol;use Thrift\Transport\TPhpStream;use Thrift\Transport\TBufferedTransport;$GEN_DIR = realpath(dirname(__FILE__)).'/gen-php';$loader  = new ThriftClassLoader();$loader->registerDefinition('HelloThrift',$GEN_DIR);$loader->register();class HelloHandler implements \HelloThrift\HelloServiceIf{    public function SayHello($username)    {        return "Php-Server: " . $username;    }}$handler   = new HelloHandler();$processor = new \HelloThrift\HelloServiceProcessor($handler);$transport = new TBufferedTransport(new TPhpStream(TPhpStream::MODE_R | TPhpStream::MODE_W));$protocol  = new TBinaryProtocol($transport,true,true);$transport->open();$processor->process($protocol,$protocol);$transport->close();
  • 建立Client.php檔案
<?php/** * Created by PhpStorm. * User: birjemin * Date: 22/02/2018 * Time: 4:00 PM */namespace  HelloThrift\php;require_once 'vendor/autoload.php';use Thrift\ClassLoader\ThriftClassLoader;use Thrift\Protocol\TBinaryProtocol;use Thrift\Transport\TSocket;use Thrift\Transport\THttpClient;use Thrift\Transport\TBufferedTransport;use Thrift\Exception\TException;$GEN_DIR = realpath(dirname(__FILE__)).'/gen-php';$loader  = new ThriftClassLoader();$loader->registerDefinition('HelloThrift', $GEN_DIR);$loader->register();if (array_search('--http',$argv)) {    $socket = new THttpClient('local.study-php.com', 80,'/Server.php');} else {    $host = explode(":", $argv[1]);    $socket = new TSocket($host[0], $host[1]);}$transport = new TBufferedTransport($socket,1024,1024);$protocol  = new TBinaryProtocol($transport);$client    = new \HelloThrift\HelloServiceClient($protocol);$transport->open();echo $client->SayHello("Php-Client");$transport->close();
  • 測試
php Client.php --http

Python測試

  • 載入thrift-python3模組(只測試python3,python2就不測試了)
pip3 install thrift
  • 產生python3版本的thrift相關檔案
thrift -r --gen py HelloThrift.thrift

這時目錄中產生了一個叫做gen-py的目錄。

  • 建立Server.py檔案
#!/usr/bin/python3# -*- coding: UTF-8 -*-import syssys.path.append('./gen-py')from HelloThrift import HelloServicefrom HelloThrift.ttypes import *from thrift.transport import TSocketfrom thrift.transport import TTransportfrom thrift.protocol import TBinaryProtocolfrom thrift.server import TServerclass HelloWorldHandler:    def __init__(self):        self.log = {}    def SayHello(self, user_name = ""):        return "Python-Server: " + user_namehandler = HelloWorldHandler()processor = HelloService.Processor(handler)transport = TSocket.TServerSocket('localhost', 9091)tfactory = TTransport.TBufferedTransportFactory()pfactory = TBinaryProtocol.TBinaryProtocolFactory()server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)server.serve()
  • 建立Client.py檔案
#!/usr/bin/python3# -*- coding: UTF-8 -*-import syssys.path.append('./gen-py')from HelloThrift import HelloServicefrom HelloThrift.ttypes import *from HelloThrift.constants import *from thrift.transport import TSocketfrom thrift.transport import TTransportfrom thrift.protocol import TBinaryProtocolhost = sys.argv[1].split(':')transport = TSocket.TSocket(host[0], host[1])transport = TTransport.TBufferedTransport(transport)protocol = TBinaryProtocol.TBinaryProtocol(transport)client = HelloService.Client(protocol)transport.open()msg = client.SayHello('Python-Client')print(msg)transport.close()
  • 測試

開一個新視窗,運行下面命令:

python3 Server.php

Go測試

  • 載入go的thrift模組
go get git.apache.org/thrift.git/lib/go/thrift
  • 產生go版本的thrift相關檔案
thrift -r --gen go HelloThrift.thrift
  • 產生Server.go檔案
package mainimport (    "./gen-go/hellothrift"    "git.apache.org/thrift.git/lib/go/thrift"    "context")const (    NET_WORK_ADDR = "localhost:9092")type HelloServiceTmpl struct {}func (this *HelloServiceTmpl) SayHello(ctx context.Context, str string) (s string, err error) {    return "Go-Server:" + str, nil}func main() {    transportFactory := thrift.NewTTransportFactory()    protocolFactory := thrift.NewTBinaryProtocolFactoryDefault()    transportFactory = thrift.NewTBufferedTransportFactory(8192)    transport, _ := thrift.NewTServerSocket(NET_WORK_ADDR)    handler := &HelloServiceTmpl{}    processor := hellothrift.NewHelloServiceProcessor(handler)    server := thrift.NewTSimpleServer4(processor, transport, transportFactory, protocolFactory)    server.Serve()}
  • 產生Client.go檔案
package mainimport (    "./gen-go/hellothrift"    "git.apache.org/thrift.git/lib/go/thrift"    "fmt"    "context"    "os")func main() {    var transport thrift.TTransport    args := os.Args    protocolFactory := thrift.NewTBinaryProtocolFactoryDefault()    transport, _ = thrift.NewTSocket(args[1])    transportFactory := thrift.NewTBufferedTransportFactory(8192)    transport, _ = transportFactory.GetTransport(transport)    //defer transport.Close()    transport.Open()    client := hellothrift.NewHelloServiceClientFactory(transport, protocolFactory)    str, _ := client.SayHello(context.Background(), "Go-Client")    fmt.Println(str)}
  • 測試

開一個新視窗,運行下面命令:

go run Server.go

綜合測試

  • 開啟兩個視窗,保證server開啟
go run Server.go # localhost:9092python3 Server.py # localhost:9091
  • php調用go-server、py-server
php Client.php localhost:9091php Client.php localhost:9092
  • python3調用go-server、py-server
python3 Client.py localhost:9091python3 Client.py localhost:9092
  • go調用go-server、py-server
go run Client.go localhost:9091go run Client.go localhost:9092

備忘

  1. 沒有測試php的socket,go、python3的http,可以花時間做一下
  2. 代碼純屬組裝,沒有深刻瞭解其中原理,後期打算寫一篇理論篇和封裝類庫篇

參考

  1. https://studygolang.com/articles/1120
  2. https://www.cnblogs.com/qufo/p/5607653.html
  3. https://www.cnblogs.com/lovemdx/archive/2012/11/22/2782180.html
  4. https://github.com/yuxel/thrift-examples
  5. http://thrift.apache.org/
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.