php实现rpc简单的方法

rpc是啥这不多解释,php扩展实现rpc

yar是鸟哥的写的扩展,实现简单的rpc.比较很好理解

windows安装yar

http://pecl.php.net/package/yar/2.0.4/windows

下载扩展,安装即可

<?php

class Test
{
    public function Hello()
    {
        return 'Hello world';
    }
}

$service = new Yar_Server(new Test);
$service->handle();
<?php

$client = new Yar_Client('http://localhost:8888/server.php');

$res = $client->Hello();

var_dump($res);

用Yar扩展实现RPC

RPC (Remote Procedure Call),远程过程调用。是一种进程间通信技术,允许程序像调用本地方法一样调用远程服务。

RPC屏蔽了数据打包、网络通信的细节,使得使用者只需要关注于服务调用,而服务调用又像调用本地方法一样自然。

PHP有个Yar扩展,提供了RPC服务端和客户端的功能。

1. 安装

$ pecl install yar

1

稍候片刻,即可装好。

然后在php.ini中加入如下一行:

extension=yar.so

1

2.Yar介绍

目前只需要关注Yar提供的两个类就行了:Yar_Server和Yar_Client。

2.1 Yar_Server

Yar_Server提供了创建RPC服务端相关的功能。该类大致如下:

Yar_Server {

/* 属性 */

protected $_executor ;

/* 方法 */

final public __construct (Object $obj)

public boolean handle (void)

}

__construct 方法接收一个对象,创建一个RPC服务,该对象的public方法便可由RPC客户端调用

handle 方法用于启动RPC服务

使用方式如下:

$server = new Yar_Server(new Service());

$server->handle();

1

2

2.2 Yar_Client

Yar_Client提供了创建RPC客户端相关的功能。该类大致如下:

Yar_Client {

/* 属性 */

protected $_protocol ;

protected $_uri ;

protected $_options ;

protected $_running ;

/* 方法 */

public void __call (string $method , array $parameters)

final public __construct (string $url)

public boolean setOpt (number $name , mixed $value)

}

__construct 方法的参数是RPC服务端对应的URL

使用方式如下:

$client = new Yar_Client("http://....");

$result = $client->someMethod($arg0, $arg1); // 调用RPC服务端中相应对象的 someMethod方法

1

2

Yar扩展的更多介绍见: http://php.net/manual/zh/book.yar.php

3. 使用示例

下面是一个在PHP框架中使用Yar创建RPC服务,然后在脚本中调用的例子。

3.1 RPC服务端

3.1.1 RPC服务类

该类是RPC服务的实际提供者。Service.php

<?php

namespace app\agent\lib;

class Service

{

public function __constrict()

{

}

public function add($a, $b)

{

return $a + $b;

}

public function sub($a, $b)

{

return $a - $b;

}

}

3.1.2 RPC包装类

用Yar扩展将上面的Service类包装成RPC服务。Rpc.php

<?php

namespace app\agent\controller;

use app\agent\lib\Service;

class Rpc extends \think\Controller

{

public function _initialize()

{

parent::_initialize();

}

public function index()

{

$rpcServer = new \Yar_Server(new Service());

$rpcServer->handle();

}

}

该RPC服务的访问路径是:

http://localhost/agent/rpc/index

1

用浏览器访问:http://localhost/agent/rpc/index:

默认情况下配置yar.expose_info是开着的,安全起见,把它关闭。

yar.expose_info = Off

1

3.2 RPC客户端

RPC客户端如下(rpc.php):

<?php

$client = new Yar_Client("https://localhost/agent/rpc/index");

try {

$result = $client->add(1, 5); // 调用RPC服务端提供的add方法

echo "result=", $result, PHP_EOL;

} catch (Exception $e) {

echo "Exception: ", $e->getMessage();

}

3.3 测试结果

命令行中运行RPC客户端:

$ php rpc.php

1

输出如下:

result=6

1

说明调用成功。