溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

php rpc的實現(xiàn)方法

發(fā)布時間:2020-09-17 10:28:00 來源:億速云 閱讀:147 作者:小新 欄目:編程語言

小編給大家分享一下php rpc的實現(xiàn)方法,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!

1.什么是rpc

RPC全稱為Remote Procedure Call,翻譯過來為“遠程過程調(diào)用”。目前,主流的平臺中都支持各種遠程調(diào)用技術(shù),以滿足分布式系統(tǒng)架構(gòu)中不同的系統(tǒng)之間的遠程通信和相互調(diào)用。遠程調(diào)用的應用場景極其廣泛,實現(xiàn)的方式也各式各樣。

2.從通信協(xié)議的層面

基于HTTP協(xié)議的(例如基于文本的SOAP(XML)、Rest(JSON),基于二進制Hessian(Binary))
基于TCP協(xié)議的(通常會借助Mina、Netty等高性能網(wǎng)絡框架)

3.從不同的開發(fā)語言和平臺層面

單種語言或平臺特定支持的通信技術(shù)(例如Java平臺的RMI、.NET平臺Remoting)
支持跨平臺通信的技術(shù)(例如HTTP Rest、Thrift等)

4.從調(diào)用過程來看

同步通信調(diào)用(同步RPC)
異步通信調(diào)用(MQ、異步RPC)

5.常見的幾種通信方式

遠程數(shù)據(jù)共享(例如:共享遠程文件,共享數(shù)據(jù)庫等實現(xiàn)不同系統(tǒng)通信)
消息隊列
RPC(遠程過程調(diào)用)

6.php實現(xiàn)簡單的rpc

目錄結(jié)構(gòu)

php rpc的實現(xiàn)方法

rpc服務端

<?php/**
 * User: yuzhao
 * CreateTime: 2018/11/15 下午11:46
 * Description: Rpc服務端
 */class RpcServer {    /**
     * User: yuzhao
     * CreateTime: 2018/11/15 下午11:51
     * @var array
     * Description: 此類的基本配置
     */
    private $params = [        'host'  => '',  // ip地址,列出來的目的是為了友好看出來此變量中存儲的信息
        'port'  => '', // 端口
        'path'  => '' // 服務目錄
    ];    /**
     * User: yuzhao
     * CreateTime: 2018/11/16 上午12:14
     * @var array
     * Description: 本類常用配置
     */
    private $config = [        'real_path' => '',        'max_size'  => 2048 // 最大接收數(shù)據(jù)大小
    ];    /**
     * User: yuzhao
     * CreateTime: 2018/11/15 下午11:50
     * @var nul
     * Description:
     */
    private $server = null;    /**
     * Rpc constructor.
     */
    public function __construct($params)
    {        $this->check();        $this->init($params);
    }    /**
     * User: yuzhao
     * CreateTime: 2018/11/16 上午12:0
     * Description: 必要驗證
     */
    private function check() {        $this->serverPath();
    }    /**
     * User: yuzhao
     * CreateTime: 2018/11/15 下午11:48
     * Description: 初始化必要參數(shù)
     */
    private function init($params) {        // 將傳遞過來的參數(shù)初始化
        $this->params = $params;        // 創(chuàng)建tcpsocket服務
        $this->createServer();
    }    /**
     * User: yuzhao
     * CreateTime: 2018/11/16 上午12:0
     * Description: 創(chuàng)建tcpsocket服務

     */
    private function createServer() {        $this->server = stream_socket_server("tcp://{$this->params['host']}:{$this->params['port']}", $errno,$errstr);        if (!$this->server) exit([
            $errno,$errstr
        ]);
    }    /**
     * User: yuzhao
     * CreateTime: 2018/11/15 下午11:57
     * Description: rpc服務目錄
     */
    public function serverPath() {
        $path = $this->params['path'];
        $realPath = realpath(__DIR__ . $path);        if ($realPath === false ||!file_exists($realPath)) {            exit("{$path} error!");
        }        $this->config['real_path'] = $realPath;
    }    /**
     * User: yuzhao
     * CreateTime: 2018/11/15 下午11:51
     * Description: 返回當前對象
     */
    public static function instance($params) {        return new RpcServer($params);
    }    /**
     * User: yuzhao
     * CreateTime: 2018/11/16 上午12:06
     * Description: 運行
     */
    public function run() {        while (true) {
            $client = stream_socket_accept($this->server);            if ($client) {                echo "有新連接\n";
                $buf = fread($client, $this->config['max_size']);
                print_r('接收到的原始數(shù)據(jù):'.$buf."\n");                // 自定義協(xié)議目的是拿到類方法和參數(shù)(可改成自己定義的)
                $this->parseProtocol($buf,$class, $method,$params);                // 執(zhí)行方法
                $this->execMethod($client, $class, $method, $params);                //關(guān)閉客戶端
                fclose($client);                echo "關(guān)閉了連接\n";
            }
        }
    }    /**
     * User: yuzhao
     * CreateTime: 2018/11/16 上午12:19
     * @param $class
     * @param $method
     * @param $params
     * Description: 執(zhí)行方法
     */
    private function execMethod($client, $class, $method, $params) {        if($class && $method) {            // 首字母轉(zhuǎn)為大寫
            $class = ucfirst($class);
            $file = $this->params['path'] . '/' . $class . '.php';            //判斷文件是否存在,如果有,則引入文件
            if(file_exists($file)) {                require_once $file;                //實例化類,并調(diào)用客戶端指定的方法
                $obj = new $class();                //如果有參數(shù),則傳入指定參數(shù)
                if(!$params) {
                    $data = $obj->$method();
                } else {
                    $data = $obj->$method($params);
                }                // 打包數(shù)據(jù)
                $this->packProtocol($data);                //把運行后的結(jié)果返回給客戶端
                fwrite($client, $data);
            }
        } else {
            fwrite($client, 'class or method error');
        }
    }    /**
     * User: yuzhao
     * CreateTime: 2018/11/16 上午12:10
     * Description: 解析協(xié)議
     */
    private function parseProtocol($buf, &$class, &$method, &$params) {
        $buf = json_decode($buf, true);
        $class = $buf['class'];
        $method = $buf['method'];
        $params = $buf['params'];
    }    /**
     * User: yuzhao
     * CreateTime: 2018/11/16 上午12:30
     * @param $data
     * Description: 打包協(xié)議
     */
    private function packProtocol(&$data) {
        $data = json_encode($data, JSON_UNESCAPED_UNICODE);
    }

}

RpcServer::instance([    'host'  => '127.0.0.1',    'port'  => 8888,    'path'  => './api'])->run();

rpc 客戶端

<?php/**
 * User: yuzhao
 * CreateTime: 2018/11/16 上午12:2
 * Description: Rpc客戶端
 */class RpcClient {    /**
     * User: yuzhao
     * CreateTime: 2018/11/16 上午12:21
     * @var array
     * Description: 調(diào)用的地址
     */
    private $urlInfo = array();    /**
     * RpcClient constructor.
     */
    public function __construct($url)
    {        $this->urlInfo = parse_url($url);
    }    /**
     * User: yuzhao
     * CreateTime: 2018/11/16 上午12:2
     * Description: 返回當前對象
     */
    public static function instance($url) {        return new RpcClient($url);
    }    public function __call($name, $arguments)
    {        // TODO: Implement __call() method.
        //創(chuàng)建一個客戶端
        $client = stream_socket_client("tcp://{$this->urlInfo['host']}:{$this->urlInfo['port']}", $errno, $errstr);        if (!$client) {            exit("{$errno} : {$errstr} \n");
        }
        $data = [            'class'  => basename($this->urlInfo['path']),            'method' => $name,            'params' => $arguments
        ];        //向服務端發(fā)送我們自定義的協(xié)議數(shù)據(jù)
        fwrite($client, json_encode($data));        //讀取服務端傳來的數(shù)據(jù)
        $data = fread($client, 2048);        //關(guān)閉客戶端
        fclose($client);        return $data;
    }
}
$cli = new RpcClient('http://127.0.0.1:8888/test');echo $cli->tuzisir1()."\n";echo $cli->tuzisir2(array('name' => 'tuzisir', 'age' => 23));

提供服務的文件

<?php/**
 * User: yuzhao
 * CreateTime: 2018/11/16 上午12:28
 * Description:
 */class Test {    public function tuzisir1() {        return '我是無參方法';
    }    public function tuzisir2($params) {        return $params;
    }
}

效果

php rpc的實現(xiàn)方法

7.RPC的注意事項

性能:影響RPC性能的主要在幾個方面:
1.序列化/反序列化的框架
2.網(wǎng)絡協(xié)議,網(wǎng)絡模型,線程模型等

安全
RPC安全的主要在于服務接口的鑒權(quán)和訪問控制支持。

跨平臺
跨不同的操作系統(tǒng),不同的編程語言和平臺。

看完了這篇文章,相信你對php rpc的實現(xiàn)方法有了一定的了解,想了解更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI