網站首頁 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
- 上一篇:沒有了
- 下一篇:沒有了
相關推薦
- 2023-03-27 React里的Fragment標簽的具體使用_React
- 2022-08-31 .Net插件框架Managed?Extensibility?Framework簡介_實用技巧
- 2023-07-07 Python Kmeans聚類挑選合適的K值可視化
- 2023-03-23 Pandas時間數據處理詳細教程_python
- 2022-09-29 python繪制柱狀圖的方法_python
- 2022-04-11 MVVMLight項目之雙向數據綁定_Android
- 2022-07-01 詳解如何在Go語言中調用C源代碼_Golang
- 2022-03-16 .NET6導入和導出EXCEL_實用技巧
- 欄目分類
-
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支