標籤:rpc 定義 分享 exists 返回結果 應用 dir image sts
RPC全稱為Remote Procedure Call,翻譯過來為"遠端程序呼叫"。主要應用於不同的系統之間的遠程通訊和相互調用。
比如有兩個系統,一個是PHP寫的,一個是JAVA寫的,而PHP想要調用JAVA中的某個類的某個方法,這時候就需要用到RPC了。
怎麼調?直接調是不可能,只能是PHP通過某種自訂協議請求JAVA的服務,JAVA解析該協議,在本地執行個體化類並調用方法,然後把結果返回給PHP。
這裡我們用PHP的socket擴充來建立一個服務端和用戶端,示範調用過程。
RpcServer.php代碼如下:
<?phpclass RpcServer { protected $serv = null; public function __construct($host, $port, $path) { //建立一個tcp socket服務 $this->serv = stream_socket_server("tcp://{$host}:{$port}", $errno, $errstr); if (!$this->serv) { exit("{$errno} : {$errstr} \n"); } //判斷我們的RPC服務類別目錄是否存在 $realPath = realpath(__DIR__ . $path); if ($realPath === false || !file_exists($realPath)) { exit("{$path} error \n"); } while (true) { $client = stream_socket_accept($this->serv); if ($client) { //這裡為了簡單,我們一次性讀取 $buf = fread($client, 2048); //解析用戶端發送過來的協議 $classRet = preg_match(‘/Rpc-Class:\s(.*);\r\n/i‘, $buf, $class); $methodRet = preg_match(‘/Rpc-Method:\s(.*);\r\n/i‘, $buf, $method); $paramsRet = preg_match(‘/Rpc-Params:\s(.*);\r\n/i‘, $buf, $params); if($classRet && $methodRet) { $class = ucfirst($class[1]); $file = $realPath . ‘/‘ . $class . ‘.php‘; //判斷檔案是否存在,如果有,則引入檔案 if(file_exists($file)) { require_once $file; //執行個體化類,並調用用戶端指定的方法 $obj = new $class(); //如果有參數,則傳入指定參數 if(!$paramsRet) { $data = $obj->$method[1](); } else { $data = $obj->$method[1](json_decode($params[1], true)); } //把運行後的結果返回給用戶端 fwrite($client, $data); } } else { fwrite($client, ‘class or method error‘); } //關閉用戶端 fclose($client); } } } public function __destruct() { fclose($this->serv); }}new RpcServer(‘127.0.0.1‘, 8888, ‘./service‘);
RpcClient.php代碼如下:
<?phpclass RpcClient { protected $urlInfo = array(); public function __construct($url) { //解析URL $this->urlInfo = parse_url($url); if(!$this->urlInfo) { exit("{$url} error \n"); } } public function __call($method, $params) { //建立一個用戶端 $client = stream_socket_client("tcp://{$this->urlInfo[‘host‘]}:{$this->urlInfo[‘port‘]}", $errno, $errstr); if (!$client) { exit("{$errno} : {$errstr} \n"); } //傳遞調用的類名 $class = basename($this->urlInfo[‘path‘]); $proto = "Rpc-Class: {$class};" . PHP_EOL; //傳遞調用的方法名 $proto .= "Rpc-Method: {$method};" . PHP_EOL; //傳遞方法的參數 $params = json_encode($params); $proto .= "Rpc-Params: {$params};" . PHP_EOL; //向服務端發送我們自訂的協議資料 fwrite($client, $proto); //讀取服務端傳來的資料 $data = fread($client, 2048); //關閉用戶端 fclose($client); return $data; }}$cli = new RpcClient(‘http://127.0.0.1:8888/test‘);echo $cli->hehe();echo $cli->hehe2(array(‘name‘ => ‘test‘, ‘age‘ => 27));
然後分別運行上面兩個指令碼(注意,php要添加環境變數)
> php RpcServer.php> php RpcClient.php
結果如下:
Test.php代碼如下:
<?phpclass Test { public function hehe() { return ‘hehe‘; } public function hehe2($params) { return json_encode($params); }}
目錄結構如下:
上面我們自訂的協議,可以隨意修改,只要是用戶端和服務端兩邊能夠統一併能解析。
用戶端通過請求服務端,把要調用的類,方法和參數傳遞給服務端,服務端去通過執行個體化調用方法返回結果。
使用PHP來簡單的建立一個RPC服務