不觉已经在开发的度过了近五年的时间,就像个小偷,偷走了我五年的岁月,也从一个懵懂新人变成有一些经验,特写下自己的一些总结。
什么是RPC??
RPC 的全称是 Remote Procedure Call 是一种进程间通信方式。它允许程序调用另一个地址空间(通常是共享网络的另一台机器上)的过程或函数,而不用程序员显式编码这个远程调用的细节。即程序员无论是调用本地的还是远程的,本质上编写的调用代码基本相同。可参考mp.weixin.qq.com/s?__biz=MjM…)
优点:
1. 简单:RPC 概念的语义十分清晰和简单,这样建立分布式计算就更容易。
2. 高效:过程调用看起来十分简单而且高效。
3. 通用:在单机计算中过程往往是不同算法部分间最重要的通信机制。
以上就是简单的总结,话不多说,自己敲一遍实现各 "hello world" 感受下
1、创建helloworld.thrift文件
//helloworld.thrift
namespace php HelloWorld
service HelloWorld{
string syaHello(1:string name);
}2、执行创建php-gen
thrift --gen php:server HelloWorld.thrift目录为:
gen-php
|----HelloWorld
| |————HelloWorld.php
| |____Types.php
HelloWorld.thrift
lib //lib为thrift源代码的lib文件3、创建服务端(server)文件和客户端(client)文件
//server.php
<?php
namespace HelloWorld\php;
error_reporting(E_ALL);
require_once __DIR__.'/lib/php/lib/Thrift/ClassLoader/ThriftClassLoader.php';
use Thrift\ClassLoader\ThriftClassLoader;
$GEN_DIR = realpath(dirname(__FILE__)).'/gen-php';
$loader = new ThriftClassLoader();
$loader->registerNamespace('Thrift',__DIR__.'/lib/php/lib');
$loader->registerDefinition('HelloWorld',$GEN_DIR);
$loader->register();
use Thrift\Exception\TException;
use Thrift\Factory\TTransportFactory;
use Thrift\Factory\TBinaryProtocolFactory;
use Thrift\Server\TServerSocket;
use Thrift\Server\TSimpleServer;
class HelloHandler implements \HelloWorld\HelloWorldIf{
public function sayHello($name){
return "hello ".$name;
}
}
try{
$handler = new HelloHandler();
$processor = new \HelloWorld\HelloWorldProcessor($handler);
$transportFactory = new TTransportFactory();
$protocolFactory = new TBinaryProtocolFactory(true, true); //以cli的方式运行,监听端口
$transport = new TServerSocket('localhost', 9090);
$server = new TSimpleServer($processor, $transport, $transportFactory, $transportFactory, $protocolFactory, $protocolFactory);
$server->serve();
}catch(TException $e){
echo "error".$e->getMessage();
}
//client.php
<?php
namespace HelloWorld\php;
error_reporting(E_ALL);
require_once __DIR__.'/lib/php/lib/Thrift/ClassLoader/ThriftClassLoader.php';
use Thrift\ClassLoader\ThriftClassLoader;
$GEN_DIR = realpath(dirname(__FILE__)).'/gen-php';
$loader = new ThriftClassLoader();
$loader->registerNamespace('Thrift',__DIR__.'/lib/php/lib');
$loader->registerDefinition('HelloWorld',$GEN_DIR);
$loader->register();
use Thrift\Protocol\TBinaryProtocol;
use Thrift\Transport\TSocket;
use Thrift\Transport\TBufferedTransport;
use Thrift\Exception\TException;
try{
$transport = new TBufferedTransport(new TSocket('localhost', 9090));
$protocol = new TBinaryProtocol($transport);
$client = new \HelloWorld\HelloWorldClient($protocol);
$transport->open();
$recv = $client->sayHello('ysp !!!');
echo $recv;
$transport->close();
}catch(TException $e){
print 'TException: '.$tx->getMessage()."\n";
}cli模式执行server文件,再执行client文件,就能看到结果: hello ysp !!!