Swoft中使用Consul微服务

9 篇文章 1 订阅
4 篇文章 0 订阅

目录

Swoft中接入Consul

Swoft服务限流

Swoft服务熔断和降级


在之前我写的一篇内容:PHP中接入consul,实现微服务的注册发现和配置中心_浮尘笔记的博客-CSDN博客 中,使用ThinkPHP6.0框架接入了微服务Consul,并且留下了一个彩蛋 “将在 swoft 框架中介入consul,实现更多微服务的功能”,那么本篇就在 Swoft 框架中使用 swoft-consul 组件,实现服务注册。官方文档:服务注册与发现 | Swoft

另外,关于Swoft的入门和基本用法可以参考上一篇内容:Swoft的注解分析和实现一个RPC服务_浮尘笔记的博客-CSDN博客,因为本篇内容的示例会基于上一篇内容的代码继续。

Swoft中接入Consul

之前的三个服务:order、goods、user中,先来修改user的内容。

修改 user/app/bean.php,添加consul的配置

//打开user服务的http配置,以及监听rpc
'httpServer' => [
    'class'    => HttpServer::class,
    'port'     => 18418,
    'listener' => [
        'rpc' => bean('rpcServer'),
    ],
],

'consul' => [
    'host' => '127.0.0.1',
    'port' => 8500,
],

修改 user/app/Listener/RegisterServiceListener.php

$service = [
    'ID' => 'swoft-user',
    'Name' => 'swoft-user',
    'Tags' => [
        'http'
    ],
    'Address' => '127.0.0.1',
    'Port' => 18408,
    'checks' => [
        [
            'name' => 'get-user-list',
            'http' => 'http://127.0.0.1:18418/consul/getList',
            'interval' => '10s',
            'timeout' => '5s',
        ]
    ],
];

// 去掉下面 Register 的注释
$this->agent->registerService($service);

在 user/app/Http/Controller/ 目录下面新增 ConsulController.php,内容如下:

<?php declare(strict_types=1);

namespace App\Http\Controller;

use Exception;
use Swoft\Co;
use Swoft\Http\Server\Annotation\Mapping\Controller;
use Swoft\Http\Server\Annotation\Mapping\RequestMapping;
use Swoft\Rpc\Client\Annotation\Mapping\Reference;

/**
 * Class ConsulController
 *
 * @since 2.0
 *
 * @Controller()
 */
class ConsulController {
    /**
     * @RequestMapping("getList")
     *
     * @return array
     */
    public function getList(): array {
        return ['getListResult' => 'OK'];
    }
}

上面的controller中仅返回一个固定的数组,用来测试注册是否成功。

接下来 consul agent -dev 先启动consul,打开浏览器输入 http://127.0.0.1:8500/ui/

然后启动 swoft的http服务,同时也会启动rpc服务,php user/bin/swoft http:start

然后去 consul 的控制台查看,swoft-user已经注册进去了

访问 http://127.0.0.1:18418/consul/getList 

至此,就在swoft中实现了服务注册的流程。 

Swoft服务限流

限流的目的是对并发访问和并发请求进行限速,或者一个时间窗口内请求进行限速从而来保护系统,一旦达到或超过限制速率就可以拒绝服务,或者进行排队等待等。常见的限流算法有:计数器、漏桶、令牌桶等,Swoft 限流器底层采用的就是令牌桶算法,底层依赖于 Redis 实现分布式限流。官方文档:服务限流 | Swoft

接下来在user服务中加上一个限流器测试一下。

修改上面的 user/app/Http/Controller/ConsulController.php

use Swoft\Limiter\Annotation\Mapping\RateLimiter;

class ConsulController
{
    /**
     * 服务限流:每秒钟访问1次,最大访问2次,以及回调函数limiterFallback
     * @RateLimiter(rate=1, max=2, fallback="limiterFallback")
     *
     * @RequestMapping("getList")
     *
     * @return array
     */
    public function getList(): array {
        return ['getListResult' => 'OK'];
    }

    /**
     * 限流的回调函数:不写业务逻辑,只返回一个错误信息
     * @return array
     */
    public function limiterFallback(): array
    {
        return ['访问次数超限'];
    }
}

启动服务 php ./bin/swoft http:start,然后访问  http://127.0.0.1:18418/consul/getList

刷新特别快的情况下就会出现报错信息

Swoft服务熔断和降级

断路器(Circuit Breaker)模式是为了防止在分布式系统中出现这种瀑布似的连锁反应导致的灾难。官方文档:服务熔断与降级 | Swoft

还是上面的 user/app/Http/Controller/ConsulController.php

use Swoft\Breaker\Annotation\Mapping\Breaker;

class ConsulController {
    /**
     * 服务降级
     * fallback 降级函数, 必须和 Breaker 标记的函数完全一样除了名称不一样且在同一个类里面
     * sucThreshold 连续成功3次状态切换阀门
     * failThreshold 连续失败1次状态切换阀门
     * timeout 超时时间2秒
     * retryTime 熔断器由开启状态到半开状态尝试切换时间 3秒
     *
     * @Breaker(fallback="funcFallback", sucThreshold=3, failThreshold=1, timeout=2.0, retryTime=3)
     * @RequestMapping("getInfo")
     * @return array
     * @throws Exception
     */
    public function getInfo(): array
    {
        //设定一个随机数,当随机数>=5的时候触发降级
        $times = rand(1, 10);
        echo $times;
        if($times >= 5){
            throw new Exception('Breaker exception');
        }
        echo ' -- OK' . PHP_EOL;
        return [
            'times' => $times,
            'result' => 'OK'
        ];
    }

    /**
     * 降级的回调函数
     * @return array
     */
    public function funcFallback(): array
    {
        echo ' -- error' . PHP_EOL;
        return ['error' => '服务已被降级'];
    }

}

启动服务 php ./bin/swoft http:start,然后访问 http://127.0.0.1:18418/consul/getInfo

随机刷新可以看到如下效果

关于Swoft接入Consul,以及在Swoft中实现服务限流和降级熔断就大概演示到这里吧,关于Swoft的更多功能可以参考官方文档。

详细代码:user/app/Http/Controller/ConsulController.php · 浮尘/swoft-demo-2023 - Gitee.com 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浮尘笔记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值