利用RateLimiter加上自定义Aop注解限制某个接口的访问频率

实际工作中有这种需求:
某个接口被不同的外部ip大量访问,且每个IP的访问频率很高。为了节约后端服务器资源,于是想通过
RateLimiter令牌桶+自定义Aop注解来限制同一ip在单位时间内只能访问固定的次数,超过这个次数的请求被拦截掉。具体实现如下:
1、自定义Aop注解

package com.fancetech.tools.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Retention(RetentionPolicy.RUNTIME)
@Target({
   ElementType.METHOD})
public @interface RequestLimitAnnotate {
   


    /**
     * 请求次数限制
     */
    long requestLimitNum();


    /**
     * 限流的时间间隔,单位秒
     */
    long timeInterval();
}

2、注解实现类

@Order(3)
@Aspect
@Component
@Slf4j
public class RequestLimitAop extends CBaseController {
   


    /**
     * 每秒产生的令牌数
     */
    private double permitsPerSecond;


	@Pointcut("@annotation(com.fancetech.tools.annotation.RequestLimitAnnotate)")
    public void 
要在Spring Boot中关闭RateLimiter,你可以采取以下步骤: 1. 导入所需的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> </dependency> ``` 2. 创建一个自定义注解,用于标记需要限流的方法: ```java import java.lang.annotation.*; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface RateLimited { String value() default ""; } ``` 3. 创建一个切面类,用于实现限流逻辑: ```java import com.google.common.util.concurrent.RateLimiter; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; @Aspect @Component public class RateLimitAspect { private final RateLimiter rateLimiter = RateLimiter.create(10); // 设置每秒最大访问次数 @Pointcut("@annotation(com.example.RateLimited)") public void rateLimited() {} @Around("rateLimited()") public Object around(ProceedingJoinPoint joinPoint) throws Throwable { if (rateLimiter.tryAcquire()) { return joinPoint.proceed(); } else { throw new RuntimeException("请求过于频繁,请稍后再试!"); } } } ``` 4. 在需要进行限流的方法上添加自定义注解: ```java import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @RateLimited // 添加此注解进行限流 @GetMapping("/my-api") public String myApi() { // 处理业务逻辑 return "Hello World!"; } } ``` 这样,当请求频率超过每秒最大访问次数时,将会抛出一个RuntimeException。你可以根据实际需求进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值