栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

hyperf 微服务配置

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

hyperf 微服务配置

  1. 克隆骨架项目,本人使用3.0项目骨架:GitHub - hyperf/biz-skeleton: Business Web Api Skeleton
  2. 安装composer组件
    composer require hyperf/rpc-client "3.0.*"
    composer require hyperf/rpc-server "3.0.*"
    composer require hyperf/service-governance "3.0.*"
    composer require hyperf/service-governance-consul "3.0.*"
  3. server.php servers配置,已省略其他配置
    [
        'name' => 'jsonrpc-http',
        'type' => ServerInterface::SERVER_HTTP,
        'host' => '0.0.0.0',
        'port' => 10080,
        'sock_type' => SWOOLE_SOCK_TCP,
        'callbacks' => [
            Event::ON_REQUEST => [HyperfJsonRpcHttpServer::class, 'onRequest'],
        ],
    ],
    [
        'name'      => 'http', // http测试接口
        'type'      => ServerInterface::SERVER_HTTP,
        'host'      => '0.0.0.0',
        'port'      => 10081,
        'sock_type' => SWOOLE_SOCK_TCP,
        'callbacks' => [
            Event::ON_REQUEST => [HyperfHttpServerServer::class, 'onRequest'],
        ],
    ]
  4. services.php配置
    return [
        'enable'    => [
            // 开启服务发现
            'discovery' => true,
            // 开启服务注册
            'register'  => true,
        ],
        // 服务消费者相关配置
        'consumers' => [
            [
                // name 需与服务提供者的 name 属性相同
                'name'          => 'CalculatorService',
                // 服务接口名,可选,默认值等于 name 配置的值,如果 name 直接定义为接口类则可忽略此行配置,如 name 为字符串则需要配置 service 对应到接口类
                'service'       => AppJsonRpcCalculatorServiceInterface::class,
                // 对应容器对象 ID,可选,默认值等于 service 配置的值,用来定义依赖注入的 key
                'id'            => AppJsonRpcCalculatorServiceInterface::class,
                // 服务提供者的服务协议,可选,默认值为 jsonrpc-http
                // 可选 jsonrpc-http jsonrpc jsonrpc-tcp-length-check
                'protocol'      => 'jsonrpc-http',
                // 负载均衡算法,可选,默认值为 random
                'load_balancer' => 'random',
                // 这个消费者要从哪个服务中心获取节点信息,如不配置则不会从服务中心获取节点信息
                'registry'      => [
                    'protocol' => 'consul',
                    'address'  => 'http://127.0.0.1:8500',
                ],
                // 如果没有指定上面的 registry 配置,即为直接对指定的节点进行消费,通过下面的 nodes 参数来配置服务提供者的节点信息
                'nodes'         => [
                    ['host' => '127.0.0.1', 'port' => 10080],
                ],
                // 配置项,会影响到 Packer 和 Transporter
                'options'       => [
                    'connect_timeout' => 5.0,
                    'recv_timeout'    => 5.0,
                    'settings'        => [
                        // 根据协议不同,区分配置
                        'open_eof_split' => true,
                        'package_eof'    => "rn",
                        // 'open_length_check' => true,
                        // 'package_length_type' => 'N',
                        // 'package_length_offset' => 0,
                        // 'package_body_offset' => 4,
                    ],
                    // 重试次数,默认值为 2,收包超时不进行重试。暂只支持 JsonRpcPoolTransporter
                    'retry_count'     => 2,
                    // 重试间隔,毫秒
                    'retry_interval'  => 100,
                    // 使用多路复用 RPC 时的心跳间隔,null 为不触发心跳
                    'heartbeat'       => 30,
                    // 当使用 JsonRpcPoolTransporter 时会用到以下配置
                    'pool'            => [
                        'min_connections' => 1,
                        'max_connections' => 32,
                        'connect_timeout' => 10.0,
                        'wait_timeout'    => 3.0,
                        'heartbeat'       => -1,
                        'max_idle_time'   => 60.0,
                    ],
                ],
            ]
        ],
        // 服务提供者相关配置
        'providers' => [],
        // 服务驱动相关配置
        'drivers'   => [
            'consul' => [
                'uri'   => 'http://127.0.0.1:8500',
                'token' => '',
                'check' => [
                    'deregister_critical_service_after' => '90m',
                    'interval'                          => '1s',
                ],
            ],
            //        'nacos'  => [
            //            // nacos server url like https://nacos.hyperf.io, Priority is higher than host:port
            //            // 'url' => '',
            //            // The nacos host info
            //            'host'         => '127.0.0.1',
            //            'port'         => 8848,
            //            // The nacos account info
            //            'username'     => null,
            //            'password'     => null,
            //            'guzzle'       => [
            //                'config' => null,
            //            ],
            //            'group_name'   => 'api',
            //            'namespace_id' => 'namespace_id',
            //            'heartbeat'    => 5,
            //            'ephemeral'    => false, // 是否注册临时实例
            //        ],
        ],
    ];
  5. 定义服务提供者interface
    interface CalculatorServiceInterface
    {
        public function add(int $a, int $b): int;
    
        public function handle(array $params): array;
    }
  6. 定义服务提供者
    use HyperfRpcServerAnnotationRpcService;
    
    #[RpcService(name: 'CalculatorService', server: 'jsonrpc-http', protocol: 'jsonrpc-http', publishTo: 'consul')]
    class CalculatorService implements CalculatorServiceInterface
    {
        // 实现一个加法方法,这里简单的认为参数都是 int 类型
        public function add(int $a, int $b): int
        {
            // 这里是服务方法的具体实现
            return $a * $b;
        }
    
        public function handle(array $params): array
        {
            return $params;
        }
    }
  7. 定义服务消费者interface
    namespace AppJsonRpc;
    
    interface CalculatorConsumerInterface
    {
        public function add(int $a, int $b): int;
    
        public function handle(array $params): array;
    }
  8. 定义服务消费者
    use HyperfRpcClientAbstractServiceClient;
    
    class CalculatorServiceConsumer extends AbstractServiceClient implements CalculatorConsumerInterface
    {
        
        protected string $serviceName = 'CalculatorService';
    
        
        protected string $protocol = 'jsonrpc-http';
    
        public function add(int $a, int $b): int
        {
            return $this->__request(__FUNCTION__, compact('a', 'b'));
        }
    
        public function handle(array $params): array
        {
            return $this->__request(__FUNCTION__, compact('params'));
        }
    }
  9. 通过http接口测试调用
    use AppJsonRpcCalculatorServiceConsumer;
    use HyperfDiAnnotationInject;
    use JetBrainsPhpStormArrayShape;
    
    class IndexController extends Controller
    {
        #[Inject]
        protected CalculatorServiceConsumer $calculatorServiceConsumer;
    
        #[ArrayShape(['code' => "int", 'data' => "int"])]
        public function index(): array
        {
            return ['code' => 200, 'data' => $this->calculatorServiceConsumer->add(2, 3)];
        }
    
        #[ArrayShape(['code' => "int", 'data' => "int"])]
        public function test(): array
        {
            return [
                'code' => 200,
                'data' => $this->calculatorServiceConsumer->handle([
                    'list'  => [],
                    'count' => []
                ])
            ];
        }
    }
  10. 调用接口测试通过:http://127.0.0.1:10081/test
  11. 安装consul:yum -y install consul
  12. 启动consul:consul agent -dev -client 0.0.0.0 -ui
  13. 浏览器访问:http://ip:8500;查看对应信息即可

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1019971.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号