Thrift-簡(jiǎn)單使用

簡(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.

Apache Thrift是一個(gè)軟件框架,用來(lái)進(jìn)行可擴(kuò)展跨語(yǔ)言的服務(wù)開發(fā),結(jié)合了軟件堆棧和代碼生成引擎,用來(lái)構(gòu)建C++,Java,Python...等語(yǔ)言,使之它們之間無(wú)縫結(jié)合、高效服務(wù)。

安裝

brew install thrift

作用

跨語(yǔ)言調(diào)用,打破不同語(yǔ)言之間的隔閡。
跨項(xiàng)目調(diào)用,微服務(wù)的么么噠。

示例

前提

  • thrift版本:


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


    http://upload.ouliu.net/i/20180223012029xj2s8.jpeg

說(shuō)明

該示例包含python,php,go三種語(yǔ)言。(java暫無(wú))

新建HelloThrift.thrift

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

內(nèi)容如下:

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

Php測(cè)試

  • 加載thrift-php庫(kù)
composer require apache/thrift
  • 生成php版本的thrift相關(guān)文件
cd /Users/birjemin/Developer/Php/study-php
thrift -r --gen php:server HelloThrift.thrift

這時(shí)目錄中生成了一個(gè)叫做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();
  • 測(cè)試
php Client.php --http
http://upload.ouliu.net/i/201802230042026zg6h.png

Python測(cè)試

  • 加載thrift-python3模塊(只測(cè)試python3,python2就不測(cè)試了)
pip3 install thrift
  • 生成python3版本的thrift相關(guān)文件
thrift -r --gen py HelloThrift.thrift

這時(shí)目錄中生成了一個(gè)叫做gen-py的目錄。

  • 建立Server.py文件
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import sys
sys.path.append('./gen-py')

from HelloThrift import HelloService
from HelloThrift.ttypes import *
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer

class HelloWorldHandler:
    def __init__(self):
        self.log = {}

    def SayHello(self, user_name = ""):
        return "Python-Server: " + user_name

handler = 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 sys
sys.path.append('./gen-py')

from HelloThrift import HelloService
from HelloThrift.ttypes import *
from HelloThrift.constants import *

from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol

host = 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()
  • 測(cè)試
    開一個(gè)新窗口,運(yùn)行下面命令:
python3 Server.php
http://upload.ouliu.net/i/20180223010050l7322.png

Go測(cè)試

  • 加載go的thrift模塊
go get git.apache.org/thrift.git/lib/go/thrift
  • 生成go版本的thrift相關(guān)文件
thrift -r --gen go HelloThrift.thrift
  • 生成Server.go文件
package main

import (
    "./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 main

import (
    "./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)
}
  • 測(cè)試
    開一個(gè)新窗口,運(yùn)行下面命令:
go run Server.go
http://upload.ouliu.net/i/20180223010517jgc30.png

綜合測(cè)試

  • 開啟兩個(gè)窗口,保證server開啟
go run Server.go # localhost:9092
python3 Server.py # localhost:9091
  • php調(diào)用go-server、py-server
php Client.php localhost:9091
php Client.php localhost:9092
  • python3調(diào)用go-server、py-server
python3 Client.py localhost:9091
python3 Client.py localhost:9092
  • go調(diào)用go-server、py-server
go run Client.go localhost:9091
go run Client.go localhost:9092

備注

  1. 沒有測(cè)試php的socket,go、python3的http,可以花時(shí)間做一下
  2. 代碼純屬組裝,沒有深刻了解其中原理,后期打算寫一篇理論篇和封裝類庫(kù)篇

參考

  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/
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容