Thrift簡單實用

簡介

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...等語言,使之它們之間無縫結合、高效服務。php

安裝

brew install thrift
複製代碼

做用

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

示例

前提

  • thrift版本: java

    https://user-gold-cdn.xitu.io/2018/2/23/161bebfd0c3d6b91?w=490&h=124&f=png&s=36953

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

    https://user-gold-cdn.xitu.io/2018/2/23/161bebfd0cfe582c?w=1016&h=688&f=png&s=318961

說明

該示例包含python,php,go三種語言。(java暫無)git

新建HelloThrift.thrift

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

內容以下:github

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的目錄。golang

  • 創建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
複製代碼

https://user-gold-cdn.xitu.io/2018/2/23/161bebfd0cf35992?w=522&h=136&f=png&s=51715

Python測試

  • 加載thrift-python3模塊(只測試python3,python2就不測試了)
pip3 install thrift
複製代碼
  • 生成python3版本的thrift相關文件
thrift -r --gen py HelloThrift.thrift
複製代碼

這時目錄中生成了一個叫作gen-py的目錄。apache

  • 創建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
複製代碼

https://user-gold-cdn.xitu.io/2018/2/23/161bebfd0cbd3bd3?w=722&h=138&f=png&s=44976

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
複製代碼

https://user-gold-cdn.xitu.io/2018/2/23/161bebfd0cb8a887?w=710&h=130&f=png&s=138549

綜合測試

  • 開啓兩個窗口,保證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
複製代碼

備註

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

參考

  1. studygolang.com/articles/11…
  2. www.cnblogs.com/qufo/p/5607…
  3. www.cnblogs.com/lovemdx/arc…
  4. github.com/yuxel/thrif…
  5. thrift.apache.org/
相關文章
相關標籤/搜索