Yar 简介
Yar 是一个轻量级, 高效的RPC框架, 它提供了一种简单方法来让PHP项目之间可以互相远程调用对方的本地方法. 并且Yar也提供了并行调用的能力. 可以支持同时调用多个远程服务的方法.
官方文档
yar官方文档地址点击查看。
github源码查看
yar安装
这里介绍两种基本安装方法
方法一:
Yar是PECL扩展,因此您可以通过以下方式简单地安装它:
pecl install yar
方法二:
编译安装:
wget -c http://pecl.php.net/get/yar-2.0.4.tgz
$/path/to/phpize
$./configure --with-php-config=/path/to/php-config/
$make && make install
在php.ini 里添加如下内容.
extension=yar.so
安装完成后
执行php -m 就可以查看到了
yar运行时的默认配置
yar.timeout //默认5000(ms)
yar.connect_timeout //默认1000(ms)
yar.packager //默认“php”,当使用--enable-msgpack构建然后默认为“msgpack”时,它应该是“php”,“json”,“msgpack”之一
yar.debug //默认关闭
yar.expose_info //默认开,是否输出GET请求的API信息
yar.content_type //默认“application / octet-stream”
yar.allow_persistent //默认关闭
注意 yar.connect_time是一个以毫秒为单位的值,在1.2.1及之前以秒为单位进行测量。
yar常量
YAR_VERSION
YAR_OPT_PACKAGER
YAR_OPT_PERSISTENT
YAR_OPT_TIMEOUT
YAR_OPT_CONNECT_TIMEOUT
YAR_OPT_HEADER //从2.0.4开始
使用范例
基本方法
Yar_Server //The Yar_Server class
Yar_Server::__construct() //创建一个HTTP RPC Server
Yar_Server::handle() //启动HTTP RPC Server
Yar_Client //The Yar_Client class
Yar_Client::__call() //调用远程服务
Yar_Client::__construct() //创建一个客户端实例
Yar_Client::setOpt() //设置调用的配置
eg:
//Set timeout to 1s
$client->SetOpt(YAR_OPT_CONNECT_TIMEOUT, 1000);
//Set packager to JSON
$client->SetOpt(YAR_OPT_PACKAGER, "json");
Yar_Concurrent_Client //The Yar_Concurrent_Client class
Yar_Concurrent_Client::call() //注册一个并行的服务调用
Yar_Concurrent_Client::loop() //发送所有注册的并行调用
Yar_Concurrent_Client::reset() //Clean all registered calls
eg:
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback");
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters")); // if the callback is not specificed,
// callback in loop will be used
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback", NULL, array(YAR_OPT_PACKAGER => "json"));
//this server accept json packager
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback", NULL, array(YAR_OPT_TIMEOUT=>1));
//custom timeout
Yar_Concurrent_Client::loop("callback", "error_callback"); //send the requests,
//the error_callback is optional
Yar_Server_Exception //The Yar_Server_Exception class
Yar_Server_Exception::getType() //获取异常的原始类型
Yar_Client_Exception //The Yar_Client_Exception class
Yar_Client_Exception::getType() //The getType purpose
具体使用方法可以参考这篇文章点击查看
遇到的问题
- 超时问题
yar RPC请求默认超时设置为 5s,因此在客户端任务请求时,若果5s内没有得到响应,请求会持续5s
修改超时时间有两种方式 (时间单位:毫秒)
1.采用ini_set()
方法实现对php.ini的动态修改
ini_set("yar.timeout",60000)
;
2.在yar注册服务方法种进行修改
Yar_Concurrent_Client::call(“http://localhost“, “some_method”, array(“parameters”), “callback”, NULL, array(YAR_OPT_TIMEOUT=>1))
;
自己测试超时时间设置为低于200毫秒时,有一定机率出现请求失败。
- 多次请求问题
在用到多次并发请求时,后续请求的结果会包含上一次请求的数据
调用Yar_Concurrent_Client::Reset()
清空第一次的请求结果,要求yar版本>=1.2.4
应用流程
简单流程图描述: