sentinel流量控制

sentinel以流量为切入点,从流量控制,熔断降级、系统负载保护等多个维度保护服务的稳定性;

应用场景:消息的削峰填谷、集群流量控制、实时熔断下游不可用应用等;

sentinel还能进行实时的监控功能。

                 

sentinel文档

 一、部署sentinel

拉取镜像: 

docker pull bladex/sentinel-dashboard:latest

 查看镜像:

docker images

 启动sentinel

 docker run --name sentinel -d -p 8858:8858 ID

启动后通过   http:// ip:8858   访问 初始账号密码都是sentinel

sentinel本质就是一个springboot应用

二、使用sentinel

 1、将依赖添加进入 common项目和网关项目中

因为网关到微服务的过程中,网关需要做限流,而且微服务本身也需要做限流,通常网关所在的机器性能需要更加强,才能承担所有微服务的管理。

    <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
    </dependency>

2、在各个微服务模块中配置sentinel

# sentinel限流配置
    sentinel:
      transport:
        dashboard: 47.100.54.149:8858
        port: 9999

配置在springcloud的下一级

sentinel是懒加载的模式,只有向访问了,才会在控制台生成记录;

3、在sentinel里面设置流控策略

4、自定义降级数据

由于异常后sentinel只是抛出一串  blocked by sentinel  ,不能具体的显示异常情况,因此需要自定义降级数据,当发生异常的时候,利用自定义异常显示异常信息。

/**
 * 这个异常处理器需要被spring进行扫描
 *
 * 具体的是通过实现 BlockExceptionHandler接口,并重写其方法
 */
@Component
public class SentinelBlockHandle implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        JsonData jsonData = null;
        // 流控异常
        if(e instanceof FlowException){
            jsonData = JsonData.buildResult(BizCodeEnum.CONTROL_FLOW);
            // 降级异常
        }else  if (e instanceof DegradeException){
            jsonData = JsonData.buildResult(BizCodeEnum.CONTROL_DEGRADE);
        }else if(e instanceof AuthorityException){
            jsonData = JsonData.buildResult(BizCodeEnum.CONTROL_AUTH);
        }

        response.setStatus(200);
        CommonUtil.sendJsonMessage(response,jsonData);
    }
}

5、限流配置持久化到

sentinel持久化配置文档

<!--        限流持久化到nacos-->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-datasource-nacos</artifactId>
        </dependency>

在common和gataway中添加。

datasource:
    ds1:
        nacos:
            server-addr: 192.168.0.88:8848
            data-id: ${spring.application.name}.json
            group-id: DEFAULT_GROUP
            data-type: json
            rule-type: flow

配置到nacos的配置中心

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

zero _s

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

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

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

打赏作者

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

抵扣说明:

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

余额充值