swoole实现简单的rpc调用

介绍

rpc 翻译过来就是远程过程调用,其实现形式有 restful api形式调用和 tcp 形式的调用。当然就性能来说,肯定是 tcp 形式的调用性能更高一些。

这里以一个 tcp 来简要讲述 rpc 的实现过程。

目录结构
│  Client.php 		// 客户端
│  composer.json	// 主要为了自动加载
│  Server.php		// 服务端
│
├─Service			// 存放各种服务的文件夹
│      CartService.php // 具体的服务类
│
└─vendor
    │  autoload.php

基本原理

rpc 使用 tcp 调用的基本原理就是将需要调用的服务类,和要调用的类中的方法,在 tcp 参数中传过来,然后在服务端解析参数,调用指定类中的方法。

演示

Client.php

service = $arguments[0];
            return $this;
        }
        $json_data = json_encode([
            'service' => $this->service,
            'action' => $name,
            'param' => $arguments[0],
        ]);
        $client = new \Swoole\Client(SWOOLE_SOCK_TCP);
        if (!$client->connect('127.0.0.1', 9501, -1)) {
            exit("connect failed. Error: {$client->errCode}\n");
        }
        $client->send($json_data);
        $result = $client->recv();
        var_dump($result);
        $client->close();
    }
}

$client = new Client();
$client->service('CartService')->getList(1);

Server.php


require_once 'vendor/autoload.php';

class Server
{
    protected $server;

    public function __construct()
    {
        $this->server = new \Swoole\Server("127.0.0.1", 9501);
        $this->onConnect();
        $this->onReceive();
        $this->onClose();
        $this->start();;
    }

    public function onConnect()
    {
        $this->server->on('Connect', function ($serv, $fd) {
            echo "Client: Connect.\n";
        });
    }

    public function onReceive()
    {
        $this->server->on('Receive', function ($serv, $fd, $from_id, $data) {
            $data = json_decode($data, true);
            $service = $data['service'];
            $action = $data['action'];
            $page = $data['param'];
            $class = "rpc\\Service\\" . $service;
            $instance = new $class;
            $result = json_encode($instance->$action($page));
            $serv->send($fd, $result);
        });
    }

    public function onClose()
    {
        $this->server->on('Close', function ($serv, $fd) {
            echo "Client: Close.\n";
        });
    }

    public function start()
    {
        $this->server->start();
    }
}

$server = new Server();

CartService.php




namespace rpc\Service;


class CartService
{
    public function getList($page)
    {
        return [
            [
                'name' => 'zhangsan',
                'sex' => $page,
            ],
            [
                'name' => 'lisi',
                'sex' => 0,
            ]
        ];
    }
}

composer.json(主要声明一下自动加载规则)

{
    "name": "gift/rpc",
    "authors": [
        {
            "name": "gift",
            "email": "[email protected]"
        }
    ],
    "require": {},
    "autoload": {
        "psr-4": {
            "rpc\\": ""
        }
    }
}
执行结果

启动服务端后,我们再执行客户端,就会收到以下的返回内容:

string(53) "[{"name":"zhangsan","sex":1},{"name":"lisi","sex":0}]"

demo下载链接:https://github.com/zhang-jianqiang/rpcdemo

你可能感兴趣的:(PHP)