日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 PHP其他 正文

php 實現rpc,使用php鏈接jsonrpc服務

作者:小吳-斌 更新時間: 2023-08-30 PHP其他

最近在學習go時,看到微服務rpc時,在想php能不能實現呢,答案是肯定的,下面寫下來記錄一下。

先看目錄結構
rpc
----api
--------Test.php
----client
--------RpcClient.php
--------RpcJsonClientGo.php
----server
--------RpcServer.php

1、外面先實現php的rpc服務

RpcServer.php

<?php

/**
 * Rpc服務端
 */
class RpcServer
{

    /**
     * 此類的基本配置
     */
    private $params = [
        'host' => '',  // ip地址,列出來的目的是為了友好看出來此變量中存儲的信息
        'port' => '', // 端口
        'path' => '' // 服務目錄
    ];
    /**
     * 本類常用配置
     */
    private $config = [
        'real_path' => '',
        'max_size' => 2048 // 最大接收數據大小
    ];

    private $server = null;

    /**
     * Rpc constructor.
     */
    public function __construct($params)
    {
        $this->check();
        $this->init($params);
    }

    /**
     * 必要驗證
     */
    private function check()
    {
        $this->serverPath();
    }

    /**
     * 初始化必要參數
     */
    private function init($params)
    {
        // 將傳遞過來的參數初始化
        $this->params = $params;
        // 創建tcpsocket服務
        $this->createServer();
    }

    /**
     * 創建tcpsocket服務
     */
    private function createServer()
    {
        $host = $this->params['host'] ?? '';
        $port = $this->params['port'] ?? 8081;
        if(empty($host)){
            exit('host error');
        }
        $this->server = stream_socket_server("tcp://{$host}:{$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;
    }

    /**
     * 返回當前對象
     */
    public static function instance($params)
    {
        return new RpcServer($params);
    }

    /**
     * 運行
     */
    public function run()
    {
        echo "開始服務......\n";
        while (true) {
            $client = stream_socket_accept($this->server);
            if ($client) {
                echo "有新連接\n";
                $buf = fread($client, $this->config['max_size']);
                print_r('接收到的原始數據:' . $buf . "\n");
                // 自定義協議目的是拿到類方法和參數(可改成自己定義的)
                $this->parseProtocol($buf, $class, $method, $params);
                // 執行方法
                $this->execMethod($client, $class, $method, $params);
                //關閉客戶端
                fclose($client);
                echo "關閉了連接\n";
            }
        }
    }

    /**
     * 執行方法
     * @param $class
     * @param $method
     * @param $params
     */
    private function execMethod($client, $class, $method, $params)
    {
        if ($class && $method) {
            // 首字母轉為大寫
            $class = ucfirst($class);
            $file = $this->params['path'] . '/' . $class . '.php';
            //判斷文件是否存在,如果有,則引入文件
            if (file_exists($file)) {
                require_once $file;
                //實例化類,并調用客戶端指定的方法
                $obj = new $class();
                //如果有參數,則傳入指定參數
                if (!$params) {
                    $data = $obj->$method();
                } else {
                    $data = $obj->$method($params);
                }
                // 打包數據
                $this->packProtocol($data);
                //把運行后的結果返回給客戶端
                fwrite($client, $data);
            }
        } else {
            fwrite($client, 'class or method error');
        }
    }

    /**
     * 解析協議
     */
    private function parseProtocol($buf, &$class, &$method, &$params)
    {
        $buf = json_decode($buf, true);
        $class = $buf['class'];
        $method = $buf['method'];
        $params = $buf['params'];
    }

    /**
     * @param $data
     * 打包協議
     */
    private function packProtocol(&$data)
    {
        $data = json_encode($data, JSON_UNESCAPED_UNICODE);
    }

}

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

Test.php

<?php

class Test
{

    public function testString()
    {
        return '測試字符串方法';
    }

    public function testParams($params)
    {
        return $params;
    }

    public function getName(){
        return 'hello word ' ;  // 返回字符串
    }
}

2、在寫客戶端

RpcClient.php

<?php

/**
 * User: yuzhao
 * CreateTime: 2018/11/16 上午12:2
 * Description: Rpc客戶端
 */
class RpcClient
{

    /**
     * User: yuzhao
     * CreateTime: 2018/11/16 上午12:21
     * @var array
     * Description: 調用的地址
     */
    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)
    {
        //創建一個客戶端
        $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
        ];
        //向服務端發送我們自定義的協議數據
        fwrite($client, json_encode($data));
        //讀取服務端傳來的數據
        $data = fread($client, 2048);
        //關閉客戶端
        fclose($client);
        return $data;
    }
}

$client = new RpcClient('http://127.0.0.1:8081/test');
echo $client->testString() . "\n";
echo $client->testParams(array('name' => 'tuzisir', 'age' => 23));

查看運行結果
在這里插入圖片描述
在這里插入圖片描述

下面跨語言連接Go的jsonrpc服務

RpcJsonClientGo.php

<?php


class RpcJsonClientGo
{
    private $conn;

    function __construct($host, $port)
    {
        $this->conn = fsockopen($host, $port, $errno, $errStr, 3);
        if (!$this->conn) {
            return false;
        }
    }

    public function Call($method, $params)
    {
        // 檢驗request信息
        if (!is_scalar($method)) {
            return "Method name has no scalar value";
        }
        if (!$this->conn) {
            return false;
        }
        $err = fwrite($this->conn, json_encode([
                'method' => $method,
                'params' => array($params),
                'id' => 0,
            ]) . "\n");
        if ($err === false) {
            return false;
        }
        stream_set_timeout($this->conn, 0, 3000);
        $line = fgetc($this->conn);
        if($line === false){
            return null;
        }
        return json_decode($line,true);
    }

}

$client = new RpcJsonClientGo("127.0.0.1",8080);
echo $client->Call(['ddd'=>22], "this is php languages");


執行php客戶端文件,在go服務端就能看到發送來的數據
在這里插入圖片描述

原文鏈接:https://blog.csdn.net/qq_23564667/article/details/126927309

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新