hyperf搭建微服務(wù) - 1

安裝 Hyperf,使用Docker運行

# 環(huán)境win10,CMD命令行窗口,執(zhí)行如下命令
# 這個容器我們用來運行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

# 設(shè)置國內(nèi)鏡像
/ # 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 服務(wù)組件
/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 

編寫一個服務(wù)提供者,映射9503端口

基于上面的hyperf-rpc-client,復(fù)制一個出來,并且命名為hyperf-rpc-service-user,作為“用戶模塊”的一個微服務(wù),下面的修改,在這個代碼的基礎(chǔ)上修改

修改配置如下 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'],
    ],
];

創(chuàng)建服務(wù)提供者

在/app目錄下新建JsonRpc目錄,并在此目錄下創(chuàng)建UserService.php、UserServiceInterface.php文件,文件內(nèi)容如下:

UserService.php

<?php

namespace App\JsonRpc;

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

/**
 * 注意,如希望通過服務(wù)中心來管理服務(wù),需在注解內(nèi)增加 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代碼

創(chuàng)建services.php、UserController.php、UserServiceInterface.php文件,文件內(nèi)容如下:

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' => [
        [
            // 用戶服務(wù)
            'name' => 'UserService',
            // 服務(wù)接口名,可選,默認值等于 name 配置的值,如果 name 直接定義為接口類則可忽略此行配置,如 name 為字符串則需要配置 service 對應(yīng)到接口類
            'service' => \App\JsonRpc\UserServiceInterface::class,
            // 服務(wù)提供者的服務(wù)協(xié)議,可選,默認值為 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 參數(shù)
        $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":"黃翠剛"}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請通過簡信或評論聯(lián)系作者。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容