最近在学习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服务端就能看到发送来的数据