Home Backend Development PHP Tutorial Things about php using thrift for server-side development

Things about php using thrift for server-side development

Oct 12, 2020 pm 02:26 PM
php thrift

php uses thrift for server-side development

Thrift uses interface description language to define and create services, and transmits data in binary format. It is smaller and more efficient. For high concurrency, Large data volumes and multi-language environments have better support.

What is Apache Thrift?

Apache Thrift is an extensible, cross-language service calling framework developed by FaceBook. To put it simply, you need to define a configuration file first. Different languages ​​can use thrift to generate servers in their respective languages ​​based on this configuration file. No matter what language the client uses, it can be called. In other words, based on the thrift protocol, Java can be used to call PHP. Serve. Currently supports calling each other between C, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, OCaml and Delphi and other languages.

Compared with traditional data transmission methods such as xml and json, thrift uses interface description language to define and create services, and transmits data in binary format. It is smaller and more efficient. For high concurrency and data volume, Large and multi-language environments have better support.

thrift installation environment requirements

  • g 4.2

  • boost 1.53.0

  • lex and yacc (based on flex and bison)

If lex and yacc are not installed, you must install them first, otherwise make will fail and prompt lex and yacc command not found error (general machines seem not to be installed, Ubuntu can use apt-get install flex bision).

Install thrift

Download the latest version of 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
Copy after login

2. Create the configure file

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

Compile options

  • Use ./configure --help to view options

  • If you want to disable a language, you can use ./configure -- without-java

thrift for php installation environment requires

  • php version >5.0, because the TBinaryProtocol protocol is used The pack() and unpack() functions are used to serialize data

  • You need to install the APC extension, because the TSocketPool class uses the apc_fetch() and apc_store() functions for apc cache operations.

When php uses thrift, in addition to copying the basic files in thrift/lib/php/lib to the project directory, you also need to copy the php files generated based on the configuration file. Go to the packages folder and introduce it into the project. This will be discussed in detail later.

Class library description

Data transmission format (protocol)

defines the transmission content and packaging of Thrift Type Unpacking, including:

  • TBinaryProtocol, binary format, TBinaryProtocolAccelerated is a fast packaging and unpacking that relies on the thrift_protocol extension.

  • TCompactProtocol, compression format

  • TJSONProtocol, JSON format

  • TMultiplexedProtocol, using the first three Data format interacts with a server that supports multiplexing protocols (providing multiple services at the same time, TMultiplexedProcessor)

Data transmission method (transport)

Defines how to send (write) and receive (read) data, including:

  • TBufferedTransport, cached transmission, written data does not start transmission immediately until the cache is refreshed.

  • TSocket, uses socket transmission

  • TFramedTransport, uses block mode for transmission, the specific transmission implementation depends on other transmission methods, such as TSocket

  • TCurlClient, uses curl to interact with the server

  • THttpClient, uses stream mode to interact with the HTTP server

  • TMemoryBuffer, use memory to exchange data

  • TPhpStream, use PHP standard input and output stream for transmission

  • TNullTransport, close data transmission

  • TSocketPool supports multiple server management based on TSocket (requires APC support) and automatically eliminates invalid servers

Development process

1. Define IDL (Interface description language) interface description file, suffix .thrift

IDL specification: http://thrift.apache.org/docs/idl

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

2. Server-side code development

3. Client-side writing access code

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()
}
Copy after login

2.shared.thrift

namespace php shared
struct SharedStruct {
  1: i32 key
  2: string value
}
service SharedService {
  SharedStruct getStruct(1: i32 key)
}
Copy after login

php server

<?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();
Copy after login

php client

<?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";
}
Copy after login

Output:

// php client.php --http
ping()
1+1=2
InvalidOperation: Cannot divide by 0
15-10=5
Log: PHP is stateless!
Copy after login

The above is the detailed content of Things about php using thrift for server-side development. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles