關於php使用thrift做服務端開發的那些事

藏色散人
發布: 2023-04-09 15:52:02
轉載
5003 人瀏覽過

php使用thrift做服務端開發

thrift採用介面描述語言定義和創建服務,用二進位格式傳輸數據,體積更小、效率更高,對於高並發、數據量大和多語言的環境有更好的支援。

Apache Thrift是啥?

Apache Thrift是FaceBook開發的一套可擴展的、跨語言的服務呼叫框架。簡單的說就是先定義一個配置文件,不同的語言可以利用thrift基於這個配置文件生成各自語言的服務端,不管客戶端用什麼語言,都可以調用,也就是說基於thrift協議用java可以調用php的服務。目前支援C , Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, OCaml and Delphi等語言之間相互呼叫。

相對於傳統的xml和json等數據傳輸方式來說,thrift採用介面描述語言定義和創建服務,用二進位格式傳輸數據,體積更小、效率更高,對於高並發、數據量大和多語言的環境有更好的支援。

thrift安裝環境需求

  • g 4.2

  • boost 1.53.0

  • lex and yacc(基於flex和bison)

#如果沒安裝lex和yacc的話要先安裝,否則會make失敗,提示lex和yacc command not found錯誤(一般的機器貌似都沒安,Ubuntu用apt-get install flex bision即可)。

安裝thrift

下載最新版thrift:

wget http://www.apache.org/dyn/closer.cgi?path=/thrift/0.9.3/thrift-0.9.3.tar.gz
tar xvf thrift-0.9.3.tar.gz
cd thrift-0.9.3
登入後複製

2.建立configure檔

// 创建./configure文件
./bootstrap.sh
// 配置并安装
./configure
make
// 检测是否有问题,如果机子没有安装python和java等可能会报错,不过本文主要讲php,安了php环境就行
make check
make install
登入後複製

編譯選項

  • 使用./configure --help可以查看選項

  • #如果想要停用某個語言,可以用./configure -- without-java

thrift for php安裝環境需求

  • php版本>5.0,因為TBinaryProtocol協定用到了pack()和unpack()函數來序列化資料

  • 需要安裝APC擴展,因為TSocketPool這個類別用到了apc_fetch()和apc_store()函數進行apc快取操作。

php使用thrift的時候,除了要將thrift/lib/php/lib裡的基礎檔copy到專案目錄下,還需要將根據設定檔產生的php檔也copy到packages資料夾下,並引入到專案中,這個後續會詳細講。

類別庫說明

資料傳輸格式(protocol)

#定義的了傳輸內容,對Thrift Type的打包解包,包括:

  • TBinaryProtocol,二進位格式,TBinaryProtocolAccelerated則是依賴thrift_protocol擴充的快速打包解包。

  • TCompactProtocol,壓縮格式

  • ##TJSONProtocol,JSON格式

  • TMultiplexedProtocol,利用前三種資料格式與支援多工協定的服務端(同時提供多個服務,TMultiplexedProcessor)互動

#資料傳輸方式(transport)

#定義如何發送(write)和接收(read)數據,包括:

  • TBufferedTransport,快取傳輸,寫入資料並不會立即開始傳輸,直到刷新快取。

  • TSocket,使用socket傳輸

  • TFramedTransport,採用分塊方式進行傳輸,具體傳輸實作依賴其他傳輸方式,例如TSocket

  • TCurlClient,使用curl與服務端互動

  • THttpClient,採用stream方式與HTTP服務端互動

  • #TMemoryBuffer,使用記憶體方式交換資料

  • TPhpStream,使用PHP標準輸入輸出流進行傳輸

  • ##TNullTransport,關閉資料傳輸
  • TSocketPool在TSocket基礎支援多個服務端管理(需要APC支援),自動剔除無效的伺服器
  • ##開發流程

1、定義IDL(Interface description language)介面描述文件,後綴.thrift

IDL規格:http://thrift.apache.org/docs/idl

thrift types:http://thrift.apache.org/docs/types

2、服務端程式碼開發

3、用戶端編寫存取程式碼

IDL :

1.tutorial.thrift

include "shared.thrift"
namespace php tutorial
typedef i32 MyInteger
const i32 INT32CONSTANT = 9853
const map<string,string> MAPCONSTANT = {&#39;hello&#39;:&#39;world&#39;, &#39;goodnight&#39;:&#39;moon&#39;}
enum Operation {
  ADD = 1,
  SUBTRACT = 2,
  MULTIPLY = 3,
  DIVIDE = 4
}
struct Work {
  1: i32 num1 = 0,
  2: i32 num2,
  3: Operation op,
  4: optional string comment,
}
exception InvalidOperation {
  1: i32 whatOp,
  2: string why
}
service Calculator extends shared.SharedService {
   void ping(),
   i32 add(1:i32 num1, 2:i32 num2),
   i32 calculate(1:i32 logid, 2:Work w) throws (1:InvalidOperation ouch),
   oneway void zip()
}
登入後複製

2.shared.thrift

namespace php shared
struct SharedStruct {
  1: i32 key
  2: string value
}
service SharedService {
  SharedStruct getStruct(1: i32 key)
}
登入後複製

php服務端

<?php
namespace tutorial\php;
ini_set(&#39;display_errors&#39;,1);
error_reporting(E_ALL);
// 引入类自动加载文件
require_once __DIR__.&#39;/../../lib/php/lib/Thrift/ClassLoader/ThriftClassLoader.php&#39;;
// 载入自动加载类
use Thrift\ClassLoader\ThriftClassLoader;
// 定义根据.thrift文件生成的php文件
$GEN_DIR = realpath(dirname(__FILE__).&#39;/..&#39;).&#39;/gen-php&#39;;
// 注册thrift服务
$loader = new ThriftClassLoader();
$loader->registerNamespace(&#39;Thrift&#39;, __DIR__ . &#39;/../../lib/php/lib&#39;);
$loader->registerDefinition(&#39;shared&#39;, $GEN_DIR);
$loader->registerDefinition(&#39;tutorial&#39;, $GEN_DIR);
$loader->register();
if (php_sapi_name() == &#39;cli&#39;) {
  ini_set("display_errors", "stderr");
}
use Thrift\Protocol\TBinaryProtocol; // 二进制格式打包解包
use Thrift\Transport\TPhpStream; // php流输入输出
use Thrift\Transport\TBufferedTransport; // 使用缓存
// 开始服务端逻辑
class CalculatorHandler implements \tutorial\CalculatorIf {
  protected $log = array();
  public function ping() {
    error_log("ping()");
  }
  // 相加
  public function add($num1, $num2) {
    error_log("add({$num1}, {$num2})");
    return $num1 + $num2;
  }
  // 枚举计算类型
  public function calculate($logid, \tutorial\Work $w) {
    error_log("calculate({$logid}, {{$w->op}, {$w->num1}, {$w->num2}})");
    switch ($w->op) {
      case \tutorial\Operation::ADD:
        $val = $w->num1 + $w->num2;
        break;
      case \tutorial\Operation::SUBTRACT:
        $val = $w->num1 - $w->num2;
        break;
      case \tutorial\Operation::MULTIPLY:
        $val = $w->num1 * $w->num2;
        break;
      case \tutorial\Operation::DIVIDE:
        if ($w->num2 == 0) {
          $io = new \tutorial\InvalidOperation();
          $io->whatOp = $w->op;
          $io->why = "Cannot divide by 0";
          throw $io;
        }
        $val = $w->num1 / $w->num2;
        break;
      default:
        $io = new \tutorial\InvalidOperation();
        $io->whatOp = $w->op;
        $io->why = "Invalid Operation";
        throw $io;
    }
    $log = new \shared\SharedStruct();
    $log->key = $logid;
    $log->value = (string)$val;
    $this->log[$logid] = $log;
    return $val;
  }
  public function getStruct($key) {
    error_log("getStruct({$key})");
    // This actually doesn&#39;t work because the PHP interpreter is
    // restarted for every request.
    //return $this->log[$key];
    return new \shared\SharedStruct(array("key" => $key, "value" => "PHP is stateless!"));
  }
  public function zip() {
    error_log("zip()");
  }
};
header(&#39;Content-Type&#39;, &#39;application/x-thrift&#39;);
if (php_sapi_name() == &#39;cli&#39;) {
  echo "\r\n";
}
$handler = new CalculatorHandler();
$processor = new \tutorial\CalculatorProcessor($handler);
// 客户端和服务端在同一个输入输出流上
//1) cli 方式:php Client.php | php Server.php 
//2) cgi 方式:利用Apache或nginx监听http请求,调用php-fpm处理,将请求转换为PHP标准输入输出流
$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();
//作为cli方式运行,非阻塞方式监听,基于libevent实现,非官方实现
//$transportFactory = new TBufferedTransportFactory();
//$protocolFactory = new TBinaryProtocolFactory(true, true);
//$transport = new TNonblockingServerSocket(&#39;localhost&#39;, 9090);
//$server = new TNonblockingServer($processor, $transport, $transportFactory, $transportFactory, $protocolFactory, $protocolFactory);
//$server->serve();
//作为cli方式运行,监听端口,官方实现
//$transportFactory = new TBufferedTransportFactory();
//$protocolFactory = new TBinaryProtocolFactory(true, true);
//$transport = new TServerSocket(&#39;localhost&#39;, 9090);
//$server = new TSimpleServer($processor, $transport, $transportFactory, $transportFactory, $protocolFactory, $protocolFactory);
//$server->serve();
登入後複製

php客戶端

<?php
namespace tutorial\php;
error_reporting(E_ALL);
require_once __DIR__.&#39;/../../lib/php/lib/Thrift/ClassLoader/ThriftClassLoader.php&#39;;
use Thrift\ClassLoader\ThriftClassLoader;
$GEN_DIR = realpath(dirname(__FILE__).&#39;/..&#39;).&#39;/gen-php&#39;;
$loader = new ThriftClassLoader();
$loader->registerNamespace(&#39;Thrift&#39;, __DIR__ . &#39;/../../lib/php/lib&#39;);
$loader->registerDefinition(&#39;shared&#39;, $GEN_DIR);
$loader->registerDefinition(&#39;tutorial&#39;, $GEN_DIR);
$loader->register();
use Thrift\Protocol\TBinaryProtocol;
use Thrift\Transport\TSocket;
use Thrift\Transport\THttpClient;
use Thrift\Transport\TBufferedTransport;
use Thrift\Exception\TException;
// 以上配置跟服务端类似
try {
  if (array_search(&#39;--http&#39;, $argv)) {
  // 使用http方式连接
    $socket = new THttpClient(&#39;localhost&#39;, 8080, &#39;/php/PhpServer.php&#39;);
  } else {
    // 使用socket连接
    $socket = new TSocket(&#39;localhost&#39;, 9090);
  }
  $transport = new TBufferedTransport($socket, 1024, 1024);
  $protocol = new TBinaryProtocol($transport);
  $client = new \tutorial\CalculatorClient($protocol);
  $transport->open();
  $client->ping();
  print "ping()\n";
  $sum = $client->add(1,1);
  print "1+1=$sum\n";
  // 调试异常情况
  $work = new \tutorial\Work();
  $work->op = \tutorial\Operation::DIVIDE;
  $work->num1 = 1;
  $work->num2 = 0;
  try {
    $client->calculate(1, $work);
    print "Whoa! We can divide by zero?\n";
  } catch (\tutorial\InvalidOperation $io) {
    print "InvalidOperation: $io->why\n";
  }
  $work->op = \tutorial\Operation::SUBTRACT;
  $work->num1 = 15;
  $work->num2 = 10;
  $diff = $client->calculate(1, $work);
  print "15-10=$diff\n";
  $log = $client->getStruct(1);
  print "Log: $log->value\n";
  $transport->close();
} catch (TException $tx) {
  print &#39;TException: &#39;.$tx->getMessage()."\n";
}
登入後複製

輸出:

// php client.php --http
ping()
1+1=2
InvalidOperation: Cannot divide by 0
15-10=5
Log: PHP is stateless!
登入後複製

以上是關於php使用thrift做服務端開發的那些事的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:csdn.net
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!