spring cloud zuul 与 sentinel的结合使用操作

spring cloud zuul 与 sentinel结合

本来大型服务处理请求超时,限流,降级熔断工作用hystrix,但是这个这个项目不再更新了,虽说它现在提供的版本不会影响到大多数开发者的使用,但是长远考虑,被更换是一件必然的事,而且现在像resilience4jSentinel这样的替代品出现,今天我们就看看使用zuul 与 Sentinel整合,实现降级与超时处理,其实网上有很多这样的教程,这里我只是做一个自己的笔记而已

1、必须的依赖

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-zuul-adapter</artifactId>
            <version>1.7.1</version>
        </dependency>

2、配置文件,其实Sentinel在这里没什么配置

server:
  port: 6001
spring:
  application:
    name: e-zuul

eureka:
  instance:
    hostname: localhost
    lease-expiration-duration-in-seconds: 90 #表示服务端多长时间没有接受到心跳信息后可以删除自己
    lease-renewal-interval-in-seconds: 30 #表示需要要向服务端发送信息,表示自己还活着
    ip-address: true
  client:
    healthcheck:
      enabled: true #客户端心跳检测
    service-url:
      defaultZone: http://${eureka.instance.hostname}:3001/eureka/

zuul:
  add-proxy-headers: true
  LogFilter:
    pre:
      disable=true:
  routes:
    e-email:
      serviceId: e-email
      path: /email/**
    e-user:
      serviceId: e-user
      path: /user/**

3、配置类, 其实配置类和后边的降级回调处理类才是关键

而且配置类中几个关于zuul与Sentinel的过滤器非常关键,这里要是不提供它们,将无法实现我们想要的功能,还有就是网关规则,可以选择qps, 超时,线程等,setGrade(RuleConstant.DEGRADE_GRADE_RT)提供选择不同的策略

package com.mjlf.ezuul.config;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.adapter.gateway.zuul.fallback.ZuulBlockFallbackManager;
import com.alibaba.csp.sentinel.adapter.gateway.zuul.filters.SentinelZuulErrorFilter;
import com.alibaba.csp.sentinel.adapter.gateway.zuul.filters.SentinelZuulPostFilter;
import com.alibaba.csp.sentinel.adapter.gateway.zuul.filters.SentinelZuulPreFilter;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.netflix.zuul.ZuulFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.Set;

@Configuration
public class ZuulConfig {
    @Bean
    public ZuulFilter sentinelZuulPreFilter() {
        // We can also provider the filter order in the constructor.
        return new SentinelZuulPreFilter();
    }

    @Bean
    public ZuulFilter sentinelZuulPostFilter() {
        return new SentinelZuulPostFilter();
    }

    @Bean
    public ZuulFilter sentinelZuulErrorFilter() {
        return new SentinelZuulErrorFilter();
    }

    @PostConstruct
    public void doInit() {
        // 注册 FallbackProvider
        ZuulBlockFallbackManager.registerProvider(new MyBlockFallbackProvider());
        initGatewayRules();
    }

    /**
     * 配置限流规则
     */
    private void initGatewayRules() {
        Set<GatewayFlowRule> rules = new HashSet<>();
        rules.add(new GatewayFlowRule("e-user").setCount(3) // 限流阈值
                .setIntervalSec(1) // 统计时间窗口,单位是秒,默认是 1 秒
        );
        rules.add(new GatewayFlowRule("e-user")
                .setGrade(RuleConstant.DEGRADE_GRADE_RT)//设置超时类型规则
                .setMaxQueueingTimeoutMs(500)
        );
        GatewayRuleManager.loadRules(rules);
    }
}

4、回调处理类,当有请求被拦截到后,就会调用降级回调方法

// 自定义 FallbackProvider
@Component
public class MyBlockFallbackProvider implements ZuulBlockFallbackProvider {
    private Logger logger = LoggerFactory.getLogger(DefaultBlockFallbackProvider.class);
    // you can define route as service level
    @Override
    public String getRoute() {
        return "*";
    }

    @Override
    public BlockResponse fallbackResponse(String route, Throwable cause) {
        RecordLog.info(String.format("[Sentinel DefaultBlockFallbackProvider] Run fallback route: %s", route));
        if (cause instanceof BlockException) {
            return new BlockResponse(429, "Sentinel block exception", route);
        } else {
            return new BlockResponse(500, "System Error", route);
        }
    }
}

zuul集成Sentinel最新的网关流控组件

一、说明

Sentinel 网关流控支持针对不同的路由和自定义的 API 分组进行流控,支持针对请求属性(如 URL 参数,Client IP,Header 等)进行流控。

Sentinel 1.6.3 引入了网关流控控制台的支持,用户可以直接在 Sentinel 控制台上查看 API Gateway 实时的 route 和自定义 API 分组监控,管理网关规则和 API 分组配置。

二、功能接入

1. 网关添加sentinel相关的jar依赖

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>

2. 网关zuul的sentinel配置

spring:
  # sentinel动态配置规则
  cloud:
    sentinel:
      zuul:
        enabled: true
        order:
          pre: 2000
          post: 500
          error: -100
      filter:
        enabled: false
      datasource:
        # 限流
        ds1:
          nacos:
            server-addr: ${zlt.nacos.server-addr}
            dataId: ${spring.application.name}-sentinel-gw-flow
            groupId: DEFAULT_GROUP
            rule-type: gw-flow
        # api分组
        ds2:
          nacos:
            server-addr: ${zlt.nacos.server-addr}
            dataId: ${spring.application.name}-sentinel-gw-api-group
            groupId: DEFAULT_GROUP
            rule-type: gw-api-group

绑定gw-flow(限流)和gw-api-group(api分组)的规则数据源为nacos
并指定nacos上对应的dataId和groupId

3. nacos规则配置

3.1. 限流配置gw-flow

Data ID:api-gateway-sentinel-gw-flow

Group:DEFAULT_GROUP

配置内容:

[
  {
    "resource": "user",
    "count": 0,
    "paramItem": {
      "parseStrategy": 3,
      "fieldName": "name"
    }
  },
  {
    "resource": "uaa_api",
    "count": 0
  }
]

规则1:所有user的请求只要参数带有name的都拦截(qps=0),user为zuul路由配置上的routeId
规则2:api分组为uaa_api的所有请求都拦截(qps=0)

3.2. api分组配置gw-api-group

Data ID:api-gateway-sentinel-gw-api-group

Group:DEFAULT_GROUP

配置内容:

[
  {
    "apiName": "uaa_api",
    "predicateItems": [
      {
        "pattern": "/user/login"
      },
      {
        "pattern": "/api-uaa/oauth/**",
        "matchStrategy": 1
      }
    ]
  }
]

上面配置意思为满足规则的api都统一分组为uaa_api
分组规则1:精准匹配/user/login
分组规则2:前缀匹配/api-uaa/oauth/**

4. 网关zuul启动参数

需要在接入端原有启动参数的基础上添加-Dcsp.sentinel.app.type=1启动以将您的服务标记为 API Gateway,在接入控制台时您的服务会自动注册为网关类型,然后您即可在控制台配置网关规则和 API 分组,例如:

java -Dcsp.sentinel.app.type=1 -jar zuul-gateway.jar

三、sentinel控制台管理

API管理(分组)

网关流控规则

四、测试限流api

1. 测试限流规则1

所有user的请求只要参数带有name的都拦截(qps=0)

不加name参数,可以访问api

后面加上name参数,请求被拦截

2. 测试限流规则2

api分组为uaa_api的所有请求都拦截(qps=0)

前缀匹配/api-uaa/oauth/**

精准匹配/user/login

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • Spring Cloud Alibaba使用Sentinel实现接口限流

    最近管点闲事浪费了不少时间,感谢网友 libinwalan 的留言提醒.及时纠正路线,继续跟大家一起学习Spring Cloud Alibaba. Nacos作为注册中心和配置中心的基础教程,到这里先告一段落,后续与其他结合的内容等讲到的时候再一起拿出来说,不然内容会有点跳跃.接下来我们就来一起学习一下Spring Cloud Alibaba下的另外一个重要组件:Sentinel. Sentinel是什么 Sentinel的官方标题是:分布式系统的流量防卫兵.从名字上来看,很容易就能猜到它是用来

  • Spring Cloud Alibaba整合Sentinel的实现步骤

    一.需求 实现一个简单的 整合 sentinel,不涉及sentinel的用法 二.实现步骤 1.下载 sentinel dashboard https://github.com/alibaba/Sentinel/releases 注意: 默认会启动8080端口,如果端口冲突,可以在启动命令上加入 -Dserver.port=新端口 默认用户名和密码[sentinel/sentinel] 启动控制台可用的配置项 2.服务提供者和消费者引入sentinel依赖 <dependency> <

  • Spring Cloud基于zuul实现网关过程解析

    这篇文章主要介绍了Spring Cloud基于zuul实现网关过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 利用zuul网关统一向外暴露接口 1.新建项目 spring-zuul 2.引入pom <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-zuu

  • spring cloud gateway整合sentinel实现网关限流

    这篇文章主要介绍了spring cloud gateway整合sentinel实现网关限流,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 说明: sentinel可以作为各微服务的限流,也可以作为gateway网关的限流组件. spring cloud gateway有限流功能,但此处用sentinel来作为替待. 说明:sentinel流控可以放在gateway网关端,也可以放在各微服务端. 1,以父工程为基础,创建子工程 2,添加pom依赖

  • spring cloud zuul 与 sentinel的结合使用操作

    spring cloud zuul 与 sentinel结合 本来大型服务处理请求超时,限流,降级熔断工作用hystrix,但是这个这个项目不再更新了,虽说它现在提供的版本不会影响到大多数开发者的使用,但是长远考虑,被更换是一件必然的事,而且现在像resilience4j, Sentinel这样的替代品出现,今天我们就看看使用zuul 与 Sentinel整合,实现降级与超时处理,其实网上有很多这样的教程,这里我只是做一个自己的笔记而已 1.必须的依赖 <dependency> <gro

  • 利用Spring Cloud Zuul实现动态路由示例代码

    前言 本文主要给大家介绍了关于Spring Cloud Zuul实现动态路由的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧. Zuul 是提供动态路由,监控,弹性,安全等的边缘服务.Zuul 相当于是设备和 Netflix 流应用的 Web 网站后端所有请求的前门. Zuul 可以适当的对多个 Amazon Auto Scaling Groups 进行路由请求. 首先新建maven项目,加入如下依赖 <dependencyManagement> <depend

  • 详解Spring Cloud Zuul重试机制探秘

    简介 本文章对应spring cloud的版本为(Dalston.SR4),具体内容如下: 开启Zuul功能 通过源码了解Zuul的一次转发 怎么开启zuul的重试机制 Edgware.RC1版本的优化 开启Zuul的功能 首先如何使用spring cloud zuul完成路由转发的功能,这个问题很简单,只需要进行如下准备工作即可: 注册中心(Eureka Server) zuul(同时也是Eureka Client) 应用服务(同时也是Eureka Client) 我们希望zuul和后端的应用

  • 详解Spring Cloud Zuul 服务网关

    有了Eureka服务注册发现.Hystrix断路器.Ribbon服务调用负载均衡,以及spring cloud config 集群配置中心,似乎一个微服务框架已五脏俱全,last but not least,一个服务网关却不可或缺. Spring Cloud Zuul路由是微服务架构的不可或缺的一部分,提供动态路由,监控,弹性,安全等的边缘服务.Zuul是Netflix出品的一个基于JVM路由和服务端的负载均衡器. Zuul介绍 在整个Spring Cloud微服务框架里,Zuul扮演着"智能网

  • Spring Cloud Zuul的重试配置详解

    Spring Cloud Zuul模块本身就包含了对于hystrix和ribbon的依赖,当我们使用zuul通过path和serviceId的组合来配置路由的时候,可以通过hystrix和ribbon的配置调整路由请求的各种时间超时机制. 1 ribbon配置举例 配置连接超时时间1秒,请求处理时间2秒,统一服务server尝试重连1次,切换server重连1次 ribbon: ConnectTimeout: 1000 ReadTimeout: 2000 MaxAutoRetries: 1 Ma

  • Spring Cloud zuul自定义统一异常处理实现方法

    Zuul在springcloud微服务体系中提供filer和router功能,是微服务不可或缺的部分.filer处理默认实现的外还可以自定义进行授权.限流.安全校验等,router完全可以替代Nginx反向代理.Zuul异常处理就是由SendErrorFilter完成. 在我们应用过程我们发现使用默认的异常filter有两个问题不是很友好: 1.无法快速识别出是否是请求路由的服务超时还是没有任何可用节点,发生错误只能查看日志通过堆栈去定位: 2.无法兼容自定义的譬如{code:500,msg:"

  • Spring Cloud Zuul路由规则动态更新解析

    这篇文章主要介绍了Spring Cloud Zuul路由规则动态更新解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 背景 Spring Cloud Zuul 作为微服务的网关,请求经过zuul路由到内部的各个service,由于存在着新增/修改/删除服务的路由规则的需求,zuul的路由规则的动态变更功能 提供了 无须重启zuul网关,即可实时更新,现有如下几种方式: 一.基于refresh + config-server事件动态刷新 (1)

  • Spring Cloud Zuul添加过滤器过程解析

    这篇文章主要介绍了Spring Cloud Zuul添加过滤器过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Zuul作为网关的其中一个重要功能,就是实现请求的鉴权.而这个动作我们往往是通过Zuul提供的过滤器来实现的. 一.过滤器方法的作用 想要使用Zuul实现过滤功能,我们需要自定义一个类继承ZuulFilter类,并实现其中的四个方法,我们先看一下这四个方法的作用是什么 public class MyFilter extends

随机推荐