SpringBoot中基于AOP和Semaphore实现API限流

 更新时间:2024年10月20日 09:04:05   作者:码到三十五  
调用速率限制是 Web API 中的常见要求,旨在防止滥用并确保公平使用资源,借助Spring Boot 中的 AOP,我们可以通过拦截方法调用并限制在特定时间范围内允许的请求数量来实现速率限制,需要的朋友可以参考下

为了在 Spring Boot 中使用 AOP 实现速率限制:

  • 定义自定义注释来标记应该限速的方法。
  • 创建一个方面类,拦截用自定义注释注释的方法调用。
  • 使用速率限制器组件来跟踪和执行速率限制。
  • 处理速率限制超出的情况,如通过抛出自定义异常。

Spring Boot API 中的速率限制

可以使用各种技术在 Spring Boot API 中实现速率限制。一种常见的方法是使用 Spring AOP来拦截传入的请求并实施速率限制。

步骤 1 - 定义速率限制配置

创建一个配置类,在其中定义速率限制参数,例如允许的请求数和时间段。

@Configuration
public class RateLimitConfig {
    @Value("${rate.limit.requests}")
    private int requests;

    @Value("${rate.limit.seconds}")
    private int seconds;

    // Getters and setters
}

步骤 2 - 创建速率限制方面

使用 Spring AOP 实现一个方面来拦截方法调用并强制执行速率限制。

@Aspect
@Component
public class RateLimitAspect {
    @Autowired
    private RateLimitConfig rateLimitConfig;

    @Autowired
    private RateLimiter rateLimiter;

    @Around("@annotation(RateLimited)")
    public Object enforceRateLimit(ProceedingJoinPoint joinPoint) throws Throwable {
        String key = getKey(joinPoint);
        if (!rateLimiter.tryAcquire(key, rateLimitConfig.getRequests(), rateLimitConfig.getSeconds())) {
            throw new RateLimitExceededException("Rate limit exceeded");
        }
        return joinPoint.proceed();
    }

    private String getKey(ProceedingJoinPoint joinPoint) {
        //为正在调用的方法生成唯一密钥
        //方法签名、用户ID、IP地址等。

    }
}

步骤 3 — 定义 RateLimited 注释

创建自定义注释来标记应受速率限制的方法。

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

步骤 4 - 实施速率限制器

创建速率限制器组件,使用令牌桶算法或任何其他合适的算法来管理速率限制。

@Component
public class RateLimiter {
    private final Map<String,RateLimitedSemaphore> semaphores = new ConcurrentHashMap<>();

    public boolean tryAcquire(String key, int requests, int seconds) {
        
        long currentTime = System.currentTimeMillis();

        // 计算时间窗口
        long startTime = currentTime - seconds * 1000;

        // 过期删除
        cleanupExpiredEntries(startTime);

        // 获取semaphore 
        RateLimitedSemaphore semaphore = semaphores.computeIfAbsent(key, k -> {
            RateLimitedSemaphore newSemaphore = new RateLimitedSemaphore(requests);
            newSemaphore.setLastAcquireTime(currentTime); // Set last acquire time
            return newSemaphore;
        });

        // 校验 semaphore 
        boolean acquired = semaphore.tryAcquire();
        if (acquired) {
            semaphore.setLastAcquireTime(currentTime); 
            // 更新
        }
        return acquired;
    }

    private void cleanupExpiredEntries(long startTime) {
        Iterator<Map.Entry<String, RateLimitedSemaphore>> iterator = semaphores.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, RateLimitedSemaphore> entry = iterator.next();
            String key = entry.getKey();
            RateLimitedSemaphore semaphore = entry.getValue();
            if (semaphore.getLastAcquireTime() < startTime) {
                iterator.remove();
            }
        }
    }

    private class RateLimitedSemaphore extends Semaphore {
        private volatile long lastAcquireTime;

        public RateLimitedSemaphore(int permits) {
            super(permits);
        }

        public long getLastAcquireTime() {
            return lastAcquireTime;
        }

        public void setLastAcquireTime(long lastAcquireTime) {
            this.lastAcquireTime = lastAcquireTime;
        }
    }
}

步骤 5 - 注释控制器方法

用注解来注释应该进行速率限制的控制器方法 @RateLimited。

@RestController
public class MyController {
    @RateLimited
    @GetMapping("/api/resource")
    public ResponseEntity<String> getResource() {
        // Implementation
    }
}

步骤 6 - 配置速率限制属性

application.properties在您的 或 中配置速率限制属性 application.yml。

rate.limit.requests=10
rate.limit.seconds=60

要按 IP 地址限制请求,可以从传入请求中提取 IP 地址并将其用作速率限制的密钥:

private String getKey(HttpServletRequest request) {
    String ipAddress = request.getRemoteAddr();
    return ipAddress; //用ID做key
}

还需要修改enforceRateLimit 中的方法 RateLimitAspect 以将对象传递 HttpServletRequest 给 getKey 方法:

@Around("@annotation(RateLimited)")
public Object enforceRateLimit(ProceedingJoinPoint joinPoint) throws Throwable {
   
    ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = requestAttributes.getRequest();

    String key = getKey(request);
    if (!rateLimiter.tryAcquire(key, rateLimitConfig.getRequests(), rateLimitConfig.getSeconds())) {
        throw new RateLimitExceededException("Rate limit exceeded");
    }
    return joinPoint.proceed();
}

以上就是SpringBoot中基于AOP和Semaphore实现API限流的详细内容,更多关于SpringBoot实现API限流的资料请关注脚本之家其它相关文章!

相关文章

  • JPA如何设置表名和实体名,表字段与实体字段的对应

    JPA如何设置表名和实体名,表字段与实体字段的对应

    这篇文章主要介绍了JPA如何设置表名和实体名,表字段与实体字段的对应,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-11-11
  • MyBatis使用注解开发和无主配置文件开发的情况

    MyBatis使用注解开发和无主配置文件开发的情况

    这篇文章主要介绍了MyBatis使用注解开发和无主配置文件开发的情况,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-03-03
  • Java Array与ArrayList区别详解

    Java Array与ArrayList区别详解

    这篇文章主要介绍了Java Array与ArrayList区别详解的相关资料,需要的朋友可以参考下
    2017-01-01
  • Java多线程通信:交替打印ABAB实例

    Java多线程通信:交替打印ABAB实例

    这篇文章主要介绍了Java多线程通信:交替打印ABAB实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-08-08
  • Java实现的剪刀石头布游戏示例

    Java实现的剪刀石头布游戏示例

    这篇文章主要介绍了Java实现的剪刀石头布游戏,涉及java随机数生成及逻辑判定等相关操作技巧,需要的朋友可以参考下
    2017-12-12
  • Java基础之三大控制流程结构

    Java基础之三大控制流程结构

    这篇文章主要介绍了Java基础之三大控制流程结构,文中有非常详细的代码示例,对正在学习java基础的小伙伴们有非常好的帮助,需要的朋友可以参考下
    2021-04-04
  • SpringBoot整合ELK做日志超完整详细教程

    SpringBoot整合ELK做日志超完整详细教程

    本文详细介绍了如何在springboot中快速接入ELK的过程,ELK可以说在实际项目中具有很好的适用价值,不管是小项目,还是中大型项目,都具备普适参考性,值得深入了解和学习,感兴趣的朋友一起看看吧
    2024-01-01
  • Android实现兼容的水波纹效果

    Android实现兼容的水波纹效果

    Android的水波纹效果只有高版本才有,我们希望自己的应用在低版本用低版本的阴影,而高版本用水波纹,这怎么做呢?下面一起来学习学习。
    2016-08-08
  • 关于Jackson的JSON工具类封装 JsonUtils用法

    关于Jackson的JSON工具类封装 JsonUtils用法

    这篇文章主要介绍了关于Jackson的JSON工具类封装 JsonUtils用法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-09-09
  • Spring实战之ServletContextResource访问资源文件示例

    Spring实战之ServletContextResource访问资源文件示例

    这篇文章主要介绍了Spring实战之ServletContextResource访问资源文件,结合实例形式分析了spring使用ServletContextResource读取与遍历资源文件相关操作技巧,需要的朋友可以参考下
    2019-12-12

最新评论