Thrift-簡單使用

2021-01-05 偶然與突然

簡介

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-php

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

測試開一個新窗口,運行下面命令: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 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)

}

測試開一個新窗口,運行下面命令:go run Server.go

綜合測試

開啟兩個窗口,保證server開啟

go run Server.go # localhost:9092

python3 Server.py # localhost:9091

php調用go-server、py-server

php Client.php localhost:9091

php Client.php localhost:9092

python3調用go-server、py-server

python3 Client.py localhost:9091

python3 Client.py localhost:9092

go調用go-server、py-server

go run Client.go localhost:9091

go run Client.go localhost:9092

備註

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

相關焦點

  • PHP使用thrift做服務端開發
    php使用thrift做服務端開發thrift採用接口描述語言定義和創建服務,用二進位格式傳輸數據
  • 從Thrift到I/O多路復用
    TBinaryProtocol:使用二進位編碼格式傳輸,Thrift的默認傳輸協議。TCompactProtocol:使用壓縮格式傳輸。TJSONProtocol:使用JSON格式傳輸。TDebugProtocol:使用文本格式傳輸,便於debug。
  • 記一次內存溢出的分析經歷,thrift帶給我的痛
    背景:有一個項目做一個系統,分客戶端和服務端,客戶端用c++寫的,用來收集信息然後傳給服務端(客戶端的數量還是比較多的,正常的有幾千個),服務端用Java寫的(帶管理頁面),屬於RPC模式,中間的通信框架使用的是thrift。
  • Hbase的安裝和基本使用
    ~/.bashrc配置Hbase打開Hbase目錄下conf/hbase-env.sh(如果沒有新建一個)vim conf/hbase-env.sh//添加下邊兩個配置export JAVA_HOME=/usr/local/src/jdk1.8.0_171 //java homeexport HBASE_MANAGES_ZK=false //是否使用自帶的
  • 雙語——舊貨店淘出的意外珍品(Thrift Store Treasures)
    * 解析中英語單詞的音標使用Dictcom和IPA雙音標標註,如果需要了解Dictcom音標,請參看我們的《dictionary.com所用的音標體系》一文。Thrift Store Treasures【譯】舊貨店珍品【單詞】Thrift 原型:thrift 名詞 [thrift][θrft] n.
  • Hadoop SQL客戶端工具之Dbeaver安裝及使用
    1文章編寫目的最近熱心網友推薦了很多Hadoop平臺的SQL客戶端工具,Fayson在前面的文章《0459-如何使用SQuirreL通過JDBC連接CDH的Hive(方式一)》、《0463-如何使用SQuirreL通過JDBC連接CDH的Hive(方式二)》和《0465-如何使用SQuirreL訪問Kerberos環境下的
  • 0644-5.16.1-如何在CDH5中使用Spark2.4 Thrift
    溫馨提示:如果使用電腦查看圖片不清晰,可以使用手機打開文章單擊文中的圖片放大查看高清原圖。
  • flume1.8 Sources類型匯總以及簡單介紹
    如果keystore和key使用不用的密碼保護,那麼ssl.key.password屬性需要提供出來:Kerberos和Kafka Sourekerberos配置文件可以在flume-env.sh通過JAVA_OPTS指定:使用SASL_PLAINTEST的安全配置示例:使用SASL_SSL的安全配置示例