SpringBoot:请求限流

本文介绍了在SpringBoot项目中使用GuavaRateLimiter进行全局限流以及自定义注解和AOP实现方法级别的请求限流,同时展示了如何结合AOP限制IP请求次数的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Spring Boot单体项目中,你可以使用以下几种方式实现请求的限流:

1. 使用Guava的RateLimiter:Guava是Google提供的一套Java库,其中包含了RateLimiter类,可以用于限制请求的速率。你可以将RateLimiter作为一个Bean注入到Spring Boot的配置类中,并在需要进行限流的方法上使用该RateLimiter。通过调整RateLimiter的参数,如请求的速率和令牌桶的容量,可以控制请求的频率

@Configuration
public class RateLimiterConfig {

    @Bean
    public RateLimiter rateLimiter() {
        return RateLimiter.create(10); // 每秒最多处理10个请求
    }
}

@RestController
public class MyController {

    @Autowired
    private RateLimiter rateLimiter;

    @GetMapping("/api/endpoint")
    public String myEndpoint() {
        if (rateLimiter.tryAcquire()) {
            // 请求通过限流
            return "Hello, World!";
        } else {
            // 请求被限制
            return "Too many requests";
        }
    }
}

2. 使用自定义注解和AOP:你可以创建一个自定义注解,例如@RateLimit,然后使用AOP将该注解织入到需要限流的方法上。在AOP切面中,可以通过计数器或令牌桶等算法来控制请求的频率。下面是一个简单的示例:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RateLimit {
    int value() default 10; // 默认每秒最多处理10个请求
}

@Aspect
@Component
public class RateLimitAspect {

    private final RateLimiter rateLimiter = RateLimiter.create(10); // 限流器

    @Around("@annotation(rateLimitAnnotation)")
    public Object rateLimit(ProceedingJoinPoint joinPoint, RateLimit rateLimitAnnotation) throws Throwable {
        if (rateLimiter.tryAcquire(rateLimitAnnotation.value())) {
            // 请求通过限流
            return joinPoint.proceed();
        } else {
            // 请求被限制
            throw new RuntimeException("Too many requests");
        }
    }
}

@RestController
public class MyController {

    @RateLimit(5) // 每秒最多处理5个请求
    @GetMapping("/api/endpoint")
    public String myEndpoint() {
        // 处理请求
        return "Hello, World!";
    }
}

通过以上两种方式,你可以在Spring Boot单体项目中实现请求的限流。根据实际需求,你可以选择适合的方式,并根据具体情况进行配置和调整。同时,要注意合理设置限流的参数,并考虑如何处理被限制的请求。

3. 要使用切面限制IP的请求次数,你可以使用AOP(面向切面编程)来实现。下面是一个示例代码,演示如何使用AOP在Spring框架中限制IP的请求次数:

首先,创建一个自定义注解,用于标记需要进行请求次数限制的方法:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestLimit {
    int maxCount() default 10;  // 最大请求次数
    long interval() default 60000;  // 时间间隔,默认为60秒
}

然后,创建一个切面类,用于处理请求次数限制的逻辑:

@Aspect
@Component
public class RequestLimitAspect {

    private ConcurrentHashMap<String, AtomicInteger> requestCountMap = new ConcurrentHashMap<>();

    @Before("@annotation(requestLimit)")
    public void requestLimit(JoinPoint joinPoint, RequestLimit requestLimit) throws Exception {
        // 获取请求的IP地址
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getRemoteAddr();

        // 获取请求的方法名
        String methodName = joinPoint.getSignature().getName();

        // 组合IP和方法名作为唯一标识
        String key = ip + ":" + methodName;

        // 如果请求次数过多,则抛出异常
        if (exceedMaxCount(key, requestLimit.maxCount())) {
            throw new Exception("请求次数过多,请稍后再试");
        }
    }

    private boolean exceedMaxCount(String key, int maxCount) {
        AtomicInteger count = requestCountMap.putIfAbsent(key, new AtomicInteger(1));
        if (count != null) {
            count.incrementAndGet();
            if (count.get() > maxCount) {
                return true;
            }
        }
        return false;
    }

    @Scheduled(fixedDelay = 60000)  // 定期清除请求次数
    public void clearRequestCount() {
        requestCountMap.clear();
    }
}

在上述代码中,使用@Before注解来标记需要在方法执行前调用的切面逻辑。在切面逻辑中,首先获取请求的IP地址和方法名,然后将其组合作为唯一标识。接着,通过exceedMaxCount方法判断请求次数是否超过了限制,如果超过则抛出异常。最后,使用@Scheduled注解定期清除请求次数,以防止数据过多。

最后,在需要进行请求次数限制的方法上添加@RequestLimit注解,并指定最大请求次数和时间间隔:

@RequestMapping("/example")
@RequestLimit(maxCount = 10, interval = 60000)
public String example() {
    // 处理请求的逻辑
}

这样,当同一个IP在指定的时间间隔内超过了最大请求次数,就会抛出异常,限制其请求次数。

请注意,上述代码只是一个简单的示例,实际使用时可能需要根据具体需求进行适当的调整。另外,切面类需要被Spring容器扫描到,可以使用@ComponentScan注解或在配置文件中配置相关扫描路径。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值