Yar 搭建 RPC 服务

版权声明:潘广宇博客, https://blog.csdn.net/panguangyuu/article/details/88379345

一、安装 Yar

pecl install yar
pecl install msgpack

二、确保 php 加载 yar 模块
 

php -m

三、编写服务器端 Server.php , 在浏览器打开 http://.../Server.php 可见API的介绍如下

<?php

class API {
    public function some_method($parameter, $options = "foo") {
        $info = "welcome, {$parameter}, ".$_SERVER['REMOTE_ADDR'];
        return json_encode(array('res' => $info));
    }

    public function demo() {
        sleep(1);
        return "123";
    }
}

四、编写客户端 Client.php , 编写完毕可 php Client.php 查看结果

<?php

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

$client->SetOpt(YAR_OPT_CONNECT_TIMEOUT, 1000);

// $client->SetOpt(YAR_OPT_HEADER, array("hd1: val"));

$result = $client->some_method("panguangyu");

print_r($result) 

// 会显示Server.php中some_method方法执行的结果

五、并发性测试 MultiClient.php , 编写完毕可 php MultiClient.php 查看结果

<?php

function callback($retval, $callinfo) {
    echo "success\n";
    var_dump($retval);
    var_dump($callinfo);
}

function error_callback($type, $error, $callinfo) {
    echo "error\n";
    error_log($error);
}

Yar_Concurrent_Client::call("http://.../Server.php", "demo", array(), "callback", "error_callback");

Yar_Concurrent_Client::call("http://.../Server.php", "demo", array(), "callback", "error_callback");

Yar_Concurrent_Client::call("http://.../Server.php", "demo", array(), "callback", "error_callback");

Yar_Concurrent_Client::loop();

六、更多参考 : https://github.com/laruence/yar

猜你喜欢

转载自blog.csdn.net/panguangyuu/article/details/88379345