萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 實現簡單 JSON-RPC 2.0 框架:服務端與客戶端完整示例

什麼是 JSON-RPC

JSON-RPC 2.0 是無狀態、輕量級遠程過程調用協議,使用 JSON 作為序列化格式,通常通過 HTTP/HTTPS 傳輸。核心概念:Request (method, params, id)、Response (result/error, id)、Notification (無 id 的請求)。

服務端實現

<?php
// JsonRpcServer.php
class JsonRpcServer {
    /**
     * 處理單個 JSON-RPC 請求
     * @param object $handler  擁有公開方法的服務對象
     * @return bool 是否為有效 JSON-RPC 請求
     */
    public static function handle(object $handler): bool {
        // 1. 校驗請求格式
        if ($_SERVER['REQUEST_METHOD'] !== 'POST' 
            || empty($_SERVER['CONTENT_TYPE']) 
            || stripos($_SERVER['CONTENT_TYPE'], 'application/json') !== 0) {
            return false;
        }

        // 2. 讀取並解析請求
        $raw = file_get_contents('php://input');
        $request = json_decode($raw, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            self::sendError(null, -32700, 'Parse error');
            return true;
        }

        // 3. 驗證必要字段
        if (!isset($request['method']) || !is_string($request['method'])) {
            self::sendError($request['id'] ?? null, -32600, 'Invalid Request: missing method');
            return true;
        }
        $params = $request['params'] ?? [];
        if (!is_array($params)) {
            self::sendError($request['id'] ?? null, -32600, 'Invalid Request: params must be array');
            return true;
        }

        // 4. 執行方法
        try {
            if (!method_exists($handler, $request['method'])) {
                throw new BadMethodCallException("Method '{$request['method']}' not found");
            }
            $refMethod = new ReflectionMethod($handler, $request['method']);
            if (!$refMethod->isPublic()) {
                throw new BadMethodCallException("Method '{$request['method']}' is not public");
            }
            $result = $refMethod->invokeArgs($handler, $params);
            self::sendResult($request['id'] ?? null, $result);
        } catch (Throwable $e) {
            self::sendError($request['id'] ?? null, -32603, $e->getMessage(), $e->getTraceAsString());
        }
        return true;
    }

    private static function sendResult($id, $result): void {
        if ($id === null) return; // Notification 無響應
        header('Content-Type: application/json');
        echo json_encode(['jsonrpc' => '2.0', 'id' => $id, 'result' => $result]);
    }

    private static function sendError($id, int $code, string $message, $data = null): void {
        header('Content-Type: application/json');
        $payload = ['jsonrpc' => '2.0', 'id' => $id, 'error' => ['code' => $code, 'message' => $message]];
        if ($data !== null) $payload['error']['data'] = $data;
        echo json_encode($payload);
    }
}

客戶端實現

<?php
// JsonRpcClient.php
class JsonRpcClient {
    private string $url;
    private int $id = 1;
    private bool $debug = false;
    private ?string $proxy = null;

    public function __construct(string $url, bool $debug = false, ?string $proxy = null) {
        $this->url = $url;
        $this->debug = $debug;
        $this->proxy = $proxy;
    }

    public function __call(string $method, array $params) {
        // 1. 構建請求
        $request = [
            'jsonrpc' => '2.0',
            'method'  => $method,
            'params'  => array_values($params), // 必須是數值索引數組
            'id'      => $this->id++,
        ];
        $payload = json_encode($request);

        // 2. 發送 HTTP 請求
        $opts = [
            'http' => [
                'method'  => 'POST',
                'header'  => "Content-Type: application/json\r\nContent-Length: " . strlen($payload),
                'content' => $payload,
                'timeout' => 10,
            ]
        ];
        if ($this->proxy) {
            $opts['http']['proxy'] = $this->proxy;
            $opts['http']['request_fulluri'] = true;
        }

        $context = stream_context_create($opts);
        $response = @file_get_contents($this->url, false, $context);
        
        if ($this->debug) {
            error_log("JRPC REQ: $payload");
            error_log("JRPC RESP: $response");
        }

        if ($response === false) {
            throw new RuntimeException("Connection failed: " . error_get_last()['message']);
        }

        // 3. 解析響應
        $resp = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new RuntimeException('Invalid JSON response');
        }

        if (!isset($resp['id']) || $resp['id'] !== $request['id']) {
            throw new RuntimeException('Response ID mismatch');
        }

        if (isset($resp['error'])) {
            $err = $resp['error'];
            throw new RuntimeException("RPC Error [{$err['code']}]: {$err['message']}", $err['code']);
        }

        return $resp['result'] ?? null;
    }
}

服務定義與使用示例

<?php
// services/UserService.php
class UserService {
    public function getName(int $id): string {
        // 模擬數據庫查詢
        return "User_$id";
    }
    public function add(int $a, int $b): int {
        return $a + $b;
    }
}

// server.php (HTTP 入口)
require 'JsonRpcServer.php';
require 'services/UserService.php';

$server = new UserService();
JsonRpcServer::handle($server); // 自動處理請求並輸出響應

// client.php
require 'JsonRpcClient.php';

$client = new JsonRpcClient('https://localhost/server.php', true);
try {
    echo $client->getName(42) . "\n";      // User_42
    echo $client->add(10, 20) . "\n";      // 30
} catch (Throwable $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

進階特性擴展

  • 批次請求:支援 [request1, request2, ...] 數組請求,服務端遍歷處理返回響應數組。
  • 異步/通知:客戶端發送無 id 的請求,服務端不返回響應。
  • 中間件:在 handle() 中加入日誌、認證、限流、熔斷。
  • Swoole/OpenSwoole:常駐內存協程服務器,吞吐量提升 100 倍,適合高頻 RPC。

總結

JSON-RPC 2.0 以 HTTP + JSON 為基礎,語言無關、防火牆友好、調試方便。上述極簡實現約 100 行代碼覆蓋核心協議,適合微服務內部調用、插件系統、跨語言橋接。生產環境建議引入 php-jsonrpc、yii2-jsonrpc 或 hyperf/jsonrpc 等成熟組件,獲得完整協議合規性、Swoole 協程支援、服務發現集成等企業級特性。

copyright © 萬盛學電腦網 all rights reserved