hyperf搭建微服务 - 1

2021-12-19  本文已影响0人  黄刚刚

安装 Hyperf,使用Docker运行

# 环境win10,CMD命令行窗口,执行如下命令
# 这个容器我们用来运行Hyperf(多映射几个端口,方便后面使用)
docker run --name hyperf_rpc -v E:\phpstudy_pro\WWW\docker\workspace\skeleton:/data/project -p 9501:9501 -p 9502:9502 -p 9503:9503  -p 9504:9504  -p 9505:9505  -p 9506:9506  -p 9507:9507  -p 9508:9508  -p 9509:9509  -it --privileged -u root --entrypoint sh hyperf/hyperf:7.4-alpine-v3.11-swoole

# 设置国内镜像
/ # composer config -g repo.packagist composer https://mirrors.aliyun.com/composer

# 进入到我们映射的主机目录
/ # cd /data/project/
# 安装 Hyperf(所有选项全部选择默认,直接回车到底)
/data/project # composer create-project hyperf/hyperf-skeleton hyperf-rpc-client

# 安装JSON RPC 服务组件
/data/project # cd hyperf-rpc-client/
/data/project/hyperf-rpc-client # composer require hyperf/json-rpc
/data/project/hyperf-rpc-client # composer require hyperf/rpc-server
/data/project/hyperf-rpc-client # composer require hyperf/rpc-client
/data/project/hyperf-rpc-client # composer require hyperf/service-governance

# 运行hyperf试试(可以看到启动成功,端口9501,并且访问成功http://127.0.0.1:9501/)
/data/project/hyperf-rpc-client # php bin/hyperf.php start 

编写一个服务提供者,映射9503端口

基于上面的hyperf-rpc-client,复制一个出来,并且命名为hyperf-rpc-service-user,作为“用户模块”的一个微服务,下面的修改,在这个代码的基础上修改

修改配置如下 config/autoload/server.php

<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
use Hyperf\Server\Event;
use Hyperf\Server\Server;
use Swoole\Constant;

return [
    'mode' => SWOOLE_PROCESS,
    'servers' => [
        [
            'name' => 'jsonrpc-http',
            'type' => Server::SERVER_HTTP,
            'host' => '0.0.0.0',
            'port' => 9503,
            'sock_type' => SWOOLE_SOCK_TCP,
            'callbacks' => [
                Event::ON_REQUEST => [\Hyperf\JsonRpc\HttpServer::class, 'onRequest'],
            ],
        ],
    ],
    'settings' => [
        Constant::OPTION_ENABLE_COROUTINE => true,
        Constant::OPTION_WORKER_NUM => swoole_cpu_num(),
        Constant::OPTION_PID_FILE => BASE_PATH . '/runtime/hyperf.pid',
        Constant::OPTION_OPEN_TCP_NODELAY => true,
        Constant::OPTION_MAX_COROUTINE => 100000,
        Constant::OPTION_OPEN_HTTP2_PROTOCOL => true,
        Constant::OPTION_MAX_REQUEST => 100000,
        Constant::OPTION_SOCKET_BUFFER_SIZE => 2 * 1024 * 1024,
        Constant::OPTION_BUFFER_OUTPUT_SIZE => 2 * 1024 * 1024,
    ],
    'callbacks' => [
        Event::ON_WORKER_START => [Hyperf\Framework\Bootstrap\WorkerStartCallback::class, 'onWorkerStart'],
        Event::ON_PIPE_MESSAGE => [Hyperf\Framework\Bootstrap\PipeMessageCallback::class, 'onPipeMessage'],
        Event::ON_WORKER_EXIT => [Hyperf\Framework\Bootstrap\WorkerExitCallback::class, 'onWorkerExit'],
    ],
];

创建服务提供者

在/app目录下新建JsonRpc目录,并在此目录下创建UserService.php、UserServiceInterface.php文件,文件内容如下:

UserService.php

<?php

namespace App\JsonRpc;

use Hyperf\RpcServer\Annotation\RpcService;
use Hyperf\Contract\ConfigInterface;

/**
 * 注意,如希望通过服务中心来管理服务,需在注解内增加 publishTo 属性
 * @RpcService(name="UserService", protocol="jsonrpc-http", server="jsonrpc-http")
 */
class UserService implements UserServiceInterface
{
    // 获取用户信息
    public function getUserInfo(int $id)
    {
        return ['id' => $id, 'name' => '黄翠刚'];
    }
}

UserServiceInterface.php

<?php

namespace App\JsonRpc;

use Hyperf\RpcServer\Annotation\RpcService;

interface UserServiceInterface
{
    public function getUserInfo(int $id);
}

启动

/data/project # cd /data/project/hyperf-rpc-service-user
/data/project/hyperf-rpc-service-user # php bin/hyperf.php start

修改hyperf-rpc-client代码

创建services.php、UserController.php、UserServiceInterface.php文件,文件内容如下:

config/autoload/services.php

<?php
declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
return [
    'consumers' => [
        [
            // 用户服务
            'name' => 'UserService',
            // 服务接口名,可选,默认值等于 name 配置的值,如果 name 直接定义为接口类则可忽略此行配置,如 name 为字符串则需要配置 service 对应到接口类
            'service' => \App\JsonRpc\UserServiceInterface::class,
            // 服务提供者的服务协议,可选,默认值为 jsonrpc-http
            'protocol' => 'jsonrpc-http',
            'nodes' => [
                // Provide the host and port of the service provider.
                ['host' => '127.0.0.1', 'port' => 9503],
            ],
        ]
];

UserController.php

<?php

declare(strict_types=1);

namespace App\Controller;

use Hyperf\HttpServer\Contract\RequestInterface;
use App\JsonRpc\UserServiceInterface;

class UserController
{

    public $userService;
    public function __construct(UserServiceInterface $userService)
    {
        $this->userService = $userService;
    }

    // 获取用户信息
    public function getUserInfo(RequestInterface $request)
    {
        // 从请求中获得 id 参数
        $id = $request->input('id', 1);
        $ret = $this->userService->getUserInfo((int)$id);
        return $ret;
    }
}

UserServiceInterface.php

<?php

namespace App\JsonRpc;

use Hyperf\RpcServer\Annotation\RpcService;

interface UserServiceInterface
{
    public function getUserInfo(int $id);
}

修改config/routes.php为如下:

<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
use Hyperf\HttpServer\Router\Router;

Router::addRoute(['GET', 'POST', 'HEAD'], '/', 'App\Controller\IndexController@index');

Router::addRoute(['GET', 'POST', 'HEAD'], '/user/getUserInfo', 'App\Controller\UserController@getUserInfo');

Router::get('/favicon.ico', function () {
    return '';
});

访问OK

http://127.0.0.1:9501/user/getUserInfo?id=5
输出:{"id":5,"name":"黄翠刚"}

上一篇 下一篇

猜你喜欢

热点阅读