【问题标题】:How to configure simple rate limiting on Spring Cloud Netflix Zuul?如何在 Spring Cloud Netflix Zuul 上配置简单的速率限制?
【发布时间】:2020-01-02 12:36:23
【问题描述】:

我的服务前面有一个简单的 Spring Cloud Netflix Zuul。我想为到达这个 Zuul 的所有请求设置 速率限制。

我看过这个帖子:https://www.baeldung.com/spring-cloud-zuul-rate-limit 但是,我的 Zuul 或 JPA 存储库中都没有控制器。 Zuul 从 Eureka 接收的所有路由。

祖尔:

@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy
public class BlitzZuulApplication {

    public static void main(String[] args) {
        SpringApplication.run(BlitzZuulApplication.class, args);
    }

}

application.properties:

spring.application.name=zuul
server.port = 7125
我的.eureka.port=7126

eureka.client.service-url.defaultZone=http://localhost:${my.eureka.port}/eureka

pom.xml:

    <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.marcosbarbero.cloud</groupId>
        <artifactId>spring-cloud-zuul-ratelimit-core</artifactId>
        <version>2.2.4.RELEASE</version>
    </dependency>

如何配置 Zuul 进行速率限制并限制总传入请求的数量?

【问题讨论】:

    标签: java spring spring-boot netflix-zuul


    【解决方案1】:

    我使用以下 application.yaml 文件:

    zuul:
      routes:
        my-service:
          path: /
      ratelimit:
        enabled: true
        repository: JPA
        policy-list:
          my-service:
            - limit: 2
              refresh-interval: 60
              type:
                - origin
      strip-prefix: true
    

    此时属性 zuul.ratelimit.repository 不应为空。如果您错过了,这里列出了一些选项。

    我开始使用 JPA 存储库。对于这个 spring-boot-starter-data-jpa 依赖项应该添加到项目中,并且应该像往常一样配置 datasource。

    如果你现在开始一个项目,你会得到这个异常:

    java.sql.SQLSyntaxErrorException: 表 'rate' 没有 存在

    在此源中,您可以在 config 文件夹中找到 Rate.java 类,其结构如下: https://www.programcreek.com/java-api-examples/?code=marcosbarbero/spring-cloud-zuul-ratelimit/spring-cloud-zuul-ratelimit-master/spring-cloud-zuul-ratelimit-core/src/main/java/com/marcosbarbero/cloud/autoconfigure/zuul/ratelimit/RateLimitAutoConfiguration.java#

    所以 Rate 实体是:

    @Entity
    public class Rate {
    
        @Id
        private String key;
        private Long remaining;
        private Long remainingQuota;
        private Long reset;
        @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy HH:mm:ss")
        private Date expiration;
    
        // constructor, getters and setters 
    }
    

    使用此配置并创建表一切正常,Zuul 将有关请求的信息保存在表中。在我的情况下,60 秒内允许 2 个请求。

    【讨论】:

    • 是否有任何可用信息/基准显示这如何影响请求吞吐量?
    猜你喜欢
    • 1970-01-01
    • 2018-08-25
    • 2016-09-30
    • 2020-04-15
    • 2020-07-19
    • 1970-01-01
    • 2021-09-07
    • 2023-03-11
    • 2016-06-05
    相关资源
    最近更新 更多