Yar是鸟哥开发的一个并行的RPC框架,用来做API再合适不过了,对于Yar的介绍可以参考鸟哥的博客:http://www.laruence.com/2012/09/15/2779.html
下面切入正题:
一、准备工作
1.安装msgpack扩展
下载:http://pecl.php.net/package/msgpack,然后上传到/usr/local目录下,安装完可以删了。1
2
3
4
5
6cd /usr/local
tar zxvf msgpack-x.x.x.tgz
cd msgpack-0.x.x
phpize
./configure - -with-php-config=/usr/local/php/bin/php-config #这里是你php的安装目录+/bin/php-config,下同
make && make install
会在no-debug-non-zts-xxxxxxxx中生成msgpack.so
在php.ini中加入extension=/usr/local/php/lib/php/extensions/no-debug-non-zts-xxxxxxxx/msgback.so
2.安装Yar扩展
下载:http://pecl.php.net/package/yar
1 | cd /usr/local |
会在no-debug-non-zts-xxxxxxxx中生成yar.so
在php.ini中加入extension=/usr/local/php/lib/php/extensions/no-debug-non-zts-xxxxxxxx/yar.so
3.重启php或apache
二、实例
1.server端代码,server.php1
2
3
4
5
6
7
8
9
10
11
class API {
public function api($parameter, $option = "foo") {
$arr = array('code'=>200,'msg'=>'成功','data'=>'返回数据');
return json_encode($arr);
}
protected function client_can_not_see() {
}
}
$service = new Yar_Server(new API());
$service->handle();
2.get请求server端时,会显示接口文档
3.客户端代码,client.php1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
error_reporting(E_ALL);
//简单的串行调用
$client = new Yar_Client("http://yar.jsyzchen.com/server.php");
$result = $client->api("parameter");
//并行化调用
function callback($retval, $callinfo) {
if ($callinfo == NULL) {
//做本地的逻辑
return TRUE;
}
echo "method: " , $callinfo['method'] , " result: ", $retval , "\n";
}
Yar_Concurrent_Client::call("http://yar.jsyzchen.com/server.php", "api", array("parameters"), "callback");
Yar_Concurrent_Client::call("http://yar.jsyzchen.com/server.php", "api", array("parameters"), "callback");
Yar_Concurrent_Client::call("http://yar.jsyzchen.com/server.php", "api", array("parameters"), "callback");
Yar_Concurrent_Client::call("http://yar.jsyzchen.com/server.php", "api", array("parameters"), "callback");
/* 发送所有注册的调用, 等待返回, 返回后Yar会调用callback回掉函数 */
Yar_Concurrent_Client::loop(); //send
4.客户端显示
三、更多Yar文档请参考http://php.net/manual/zh/book.yar.php