首页 > 解决方案 > 如何在 Spring Boot 中应用基于 IP 的速率限制

问题描述

我想为我的项目的每个(/get)服务应用基于 IP 的速率限制,例如每个 IP 可以访问特定编号的每个服务。时间,即 5 次/10 秒。我使用了 bucket4j 速率限制,但它不起作用。有没有人对此有任何想法?

这是我的 application.properties

spring.cache.jcache.config=classpath:ehcache.xml
logging.level.org.ehcache=info
bucket4j.enabled=true
bucket4j.filters[0].cache-name=buckets
bucket4j.filters[0].filter-method=servlet
bucket4j.filters[0].url=.* 
bucket4j.filters[0].rate-limits[0].bandwidths[0].capacity=5
bucket4j.filters[0].rate-limits[0].bandwidths[0].time=10
bucket4j.filters[0].rate-limits[0].bandwidths[0].unit=seconds
bucket4j.filters[0].rate-limits[0].expression="getRemoteAddress()"
bucket4j.filters[0].rate-limits[0].bandwidths[0].fixed-refill-interval=0
bucket4j.filters[0].rate-limits[0].bandwidths[0].fixed-refill-interval-unit=seconds

这是encache.xml

<config xmlns='http://www.ehcache.org/v3'
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:jsr107="http://www.ehcache.org/v3/jsr107"
        xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd
        http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.0.xsd">
    <cache alias="buckets">
        <expiry><ttl unit="seconds">6</ttl></expiry>
        <heap unit="entries">2000</heap>
        <jsr107:mbeans enable-statistics="true"/>
    </cache>
</config>

pom.xml

<dependency>
    <groupId>com.giffing.bucket4j.spring.boot.starter</groupId>
    <artifactId>bucket4j-spring-boot-starter</artifactId>
    <version>0.2.0</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>

<dependency>
    <groupId>javax.cache</groupId>
    <artifactId>cache-api</artifactId>
    <scope>runtime</scope>
</dependency>

服务器初始化器

@EnableCaching
public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(EwseparationApplication.class);
    }

}

标签: javaspringspring-bootspring-securitythrottling

解决方案


我遇到了同样的问题。看起来bucket4j spring boot starter github项目有一个关于这个(链接)的问题。

我将我的 application.properties 转换为 application.yml 作为问题中报告的个人并且我的速率限制开始工作。我不确定实际问题是什么(为什么 application.yml 有效而 application.properties 无效)。我有点喜欢 yml 的属性格式。


推荐阅读