Sentinel+Gateway网关流控规则持久化到文件

Sentinel+Gateway 网关流控规则持久化到文件

提示

网关流控规则 != 流控规则

版本声明

<java.version>1.8</java.version>
<spring.boot.version>2.3.2.RELEASE</spring.boot.version>
<spring.cloud.version>Hoxton.SR8</spring.cloud.version>
<spring.cloud.alibaba.version>2.2.5.RELEASE</spring.cloud.alibaba.version>

sentinel控制台1.8.0

配置类

@Configuration
public class SentinelConfig {

    /**
     * 自定义全局fallback
     *
     * @return 全局网关限流处理逻辑
     * @see com.alibaba.cloud.sentinel.gateway.scg.SentinelSCGAutoConfiguration#init()
     * @see com.alibaba.cloud.sentinel.gateway.scg.SentinelSCGAutoConfiguration#initFallback()
     * @see com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager#blockHandler
     */
    public SentinelConfig() {
        GatewayCallbackManager.setBlockHandler(
                (exchange, ex) -> ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
                                          .contentType(MediaType.APPLICATION_JSON)
                                          .body(fromValue(ReturnResult.error().code(429).message("限流")))
        );
    }

    /**
     * 动态规则,pull模式
     * 
     * @throws Exception
     * @see com.alibaba.cloud.sentinel.custom.SentinelAutoConfiguration#init 行:133,134
     * @see com.alibaba.csp.sentinel.init.InitExecutor#doInit 行:46,53
     * @see com.alibaba.csp.sentinel.transport.init.CommandCenterInitFunc#init 行:32,40
     * @see com.alibaba.csp.sentinel.transport.command.SimpleHttpCommandCenter#start 行:87,106
     * @see com.alibaba.csp.sentinel.transport.command.SimpleHttpCommandCenter.ServerThread#run 行:185,190,191
     * @see com.alibaba.csp.sentinel.transport.command.http.HttpEventTask#run 行:101,103
     * @see com.alibaba.csp.sentinel.adapter.gateway.common.command.UpdateGatewayRuleCommandHandler#handle 行:39,60,90
     */
    @PostConstruct
    public void dynamicGatewayFlowRule() throws Exception {
        //没有则建立
        String flowRulePath = "E:\\harmony\\springcloudalibabademo\\gateway\\src\\main\\resources\\gateway-flow-rule.json";
        ReadableDataSource<String, Set<GatewayFlowRule>> ds = new FileRefreshableDataSource<>(
                flowRulePath, source -> JSON.parseObject(source, new TypeReference<Set<GatewayFlowRule>>() {
        })
        );
        // 将可读数据源注册至 GatewayRuleManager(gateway相关规则)
        // 这样当规则文件发生变化时,就会更新规则到内存
        GatewayRuleManager.register2Property(ds.getProperty());
        // 收到控制台推送的规则时,Sentinel 会先更新到内存,然后将规则写入到文件中.
        WritableDataSource<Set<GatewayFlowRule>> wds = new FileWritableDataSource<>(flowRulePath, (t) -> JSON.toJSONString(t));
        UpdateGatewayRuleCommandHandler.setWritableDataSource(wds);
    }
}

持久化文件

/src/main/resources
在目录下创建gateway-flow-rule.json保存网关流控规则

配置文件

server:
  port: 80

spring:
  jackson:
    time-zone: GMT+8
    date-format: yyyy-MM-dd HH:mm:ss
  application:
    name: gateway
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
    sentinel:
      transport:
        dashboard: 127.0.0.1:1716
        port: 1719
    #     https://github.com/alibaba/Sentinel/wiki/在生产环境中使用-Sentinel
    #     sentinel限流规则持久化在文件中
    #    只能读并发送到sentinel控制台显示,在控制台的操作并不能修改文件
    #      datasource.ds1.file:
    #        file: "classpath: gateway-flow-rule.json"
    #        ruleType: gw-flow
    #        自定义fallback方式一
    #        @see com.alibaba.cloud.sentinel.gateway.scg.SentinelSCGAutoConfiguration.initFallback
    #      scg:
    #        fallback:
    #          mode: response
    #          content-type: application/json
    #          response-status: 429
    #          response-body: '{"code":429,"message":"限流"}'
    gateway:
      routes:
        - id: nodeone
          uri: lb://nodeone
          predicates:
            - Path=/nodeone/**
          filters:
            - StripPrefix=1
        - id: nodetwo
          uri: lb://nodetwo
          predicates:
            - Path=/nodetwo/**
          filters:
            - StripPrefix=1
        - id: gateway
          uri: lb://gateway
          predicates:
            - Path=/gateway/**
          filters:
            - StripPrefix=0

management:
  endpoints:
    web:
      exposure:
        include: "*"

核心依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

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

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

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>2.2.5.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Hoxton.SR8</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值