使用AOP+ExpiringMap+ConcurrentHashMap实现对接口访问次数的限制

什么是ExpiringMap

ExpiringMap 是一个Java库中的数据结构,主要用于实现具有自动过期功能的Map(键值对集合)。在常规的java.util.Map基础上,ExpiringMap 提供了额外的功能,即它可以为存储在其中的键值对设置生命周期(TTL,Time to Live),一旦超过设定的生存时间,相应的键值对会自动从Map中移除。

ExpiringMap的主要特点包括:

  1. 过期策略:允许为Map中的条目设置固定或可变的有效期。
  2. 线程安全:确保在多线程环境下也能正确地进行读写操作。
  3. 高性能低开销:设计用于高效处理大量并发访问及条目的过期清理。
  4. 零依赖:通常不需要外部依赖库即可运行。
  5. 最大尺寸限制:可以设置Map的最大容量,当达到上限时可以通过某种策略(如LRU)删除最早过期或者最先插入的条目。
  6. 过期监听器:提供过期事件监听机制,当某个条目过期时可以执行特定的回调函数。
  7. 延迟输入加载:某些实现可能支持在访问时才计算或加载即将过期的数据。
  8. 过期自省:允许查询Map中已经过期但尚未被清理的条目。

通过ExpiringMap,开发者可以在应用程序中方便地创建一个本地缓存,用于存储需要在一段时间后失效的数据,从而避免频繁的数据库访问或者其他昂贵资源的操作。这个数据结构在Web服务限流、缓存管理、临时授权令牌存储等方面尤其有用。

过期策略:

  • ExpirationPolicy.CREATED:在每次更新元素时,过期时间同时清零。
  • ExpirationPolicy.ACCESSED:在每次访问元素时,过期时间同时清零。

什么是ConcurrentHashMap

ConcurrentHashMap 是 Java 中提供的线程安全的哈希表实现类。它继承自 AbstractMap 类,实现了 ConcurrentMap 接口,是 HashMap 的线程安全版本。

与 HashMap 不同的是,ConcurrentHashMap 在处理并发操作时采用了一种不同的策略来保证线程安全性。它使用了分段锁(Segment)的机制,将整个哈希表分为多个段(Segment),每个段都可以独立地加锁,不同的线程可以同时访问不同的段,从而提高了并发访问的效率。

ConcurrentHashMap 主要提供了以下特点和方法:

  1. 线程安全:ConcurrentHashMap 在多线程环境下提供了线程安全的操作。
  2. 分段锁:它使用了分段锁的机制,不同的线程可以同时访问不同的段,提高了并发访问的效率。
  3. 高性能:相较于传统的线程安全的哈希表实现(如 Hashtable),ConcurrentHashMap 在并发访问下具有更好的性能。
  4. 支持高并发读写:ConcurrentHashMap 在读操作上没有锁的限制,多个线程可以同时读取数据,从而提高了并发读取的效率。
  5. 支持扩容:ConcurrentHashMap 在容量不足时,可以自动进行扩容操作,以保证哈希表的性能。

以下是 ConcurrentHashMap 的一些常用方法:

  • put(key, value):将指定的键值对添加到哈希表中。
  • get(key):根据指定的键获取对应的值。
  • remove(key):根据指定的键删除对应的键值对。
  • containsKey(key):判断哈希表中是否包含指定的键。
  • size():返回哈希表中键值对的数量。

需要注意的是,虽然 ConcurrentHashMap 提供了线程安全的操作,但在一些特殊情况下,仍然需要额外的同步措施来保证数据的一致性。

实现接口访问次数限制

添加依赖

<!-- AOP依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
    <version>2.1.5.RELEASE</version>
</dependency>
<!-- Map依赖 -->
<dependency>
    <groupId>net.jodah</groupId>
    <artifactId>expiringmap</artifactId>
    <version>0.5.8</version>
</dependency>

自定义注解

package com.sitech.salemng.common.aop;

import java.lang.annotation.*;

/**
 * @author sxh
 * @date 2024/3/14
 */
@Documented
@Target(ElementType.METHOD) // 说明该注解只能放在方法上面
@Retention(RetentionPolicy.RUNTIME)
public @interface LimitRequest {
    long time() default 60*60*1000; // 限制时间 单位:毫秒
    int count() default 5; // 允许请求的次数
}

自定义切面AOP

package com.sitech.salemng.common.aop;

import com.sitech.ijcf.boot.core.error.exception.BusiException;
import net.jodah.expiringmap.ExpirationPolicy;
import net.jodah.expiringmap.ExpiringMap;
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;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author sxh
 * @date 2024/3/14
 */
@Aspect
@Component
public class LimitRequestAspect {

    private static ConcurrentHashMap<String, ExpiringMap<String, Integer>> book = new ConcurrentHashMap<>();

    // 定义切点
    // 让所有有@LimitRequest注解的方法都执行切面方法
    @Pointcut("@annotation(limitRequest)")
    public void excudeService(LimitRequest limitRequest) {
    }

    @Around("excudeService(limitRequest)")
    public Object doAround(ProceedingJoinPoint pjp, LimitRequest limitRequest) throws Throwable {

        // 获得request对象
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();

        // 获取Map对象, 如果没有则返回默认值
        // 第一个参数是key, 第二个参数是默认值
        ExpiringMap<String, Integer> uc = book.getOrDefault(request.getRequestURI(), ExpiringMap.builder().variableExpiration().build());
        Integer uCount = uc.getOrDefault(request.getRemoteAddr(), 0);
        System.out.println("uCount = " + uCount);
        System.out.println("请求IP:" + request.getRemoteAddr());


        if (uCount >= limitRequest.count()) { // 超过次数,不执行目标方法
            System.out.println("请求接口超过次数!!!");
            throw new BusiException("请求接口超过次数!!!");
        } else if (uCount == 0) { // 第一次请求时,设置有效时间
            uc.put(request.getRemoteAddr(), uCount + 1, ExpirationPolicy.CREATED, limitRequest.time(), TimeUnit.MILLISECONDS);
        } else { // 未超过次数, 记录加一
            uc.put(request.getRemoteAddr(), uCount + 1);
        }
        book.put(request.getRequestURI(), uc);
        System.out.println("book" + book);


        // result的值就是被拦截方法的返回值
        Object result = pjp.proceed();

        return result;
    }


}

最后,需要限制哪个接口的访问次数,就在该方法上添加@LimitRequest注解。

  • 17
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
实现接口调用频率限制可以使用AOPConcurrentHashMap结合的方式。 首先,在Spring Boot中,我们可以使用AOP来拦截接口的调用。我们可以定义一个切面,使用@Aspect注解标注,然后在切入点方法中定义需要拦截的注解。 例如,我们可以定义一个@FrequencyLimit注解,用于标注需要限制调用频率的方法: ```java @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.METHOD }) public @interface FrequencyLimit { // 限制时间段,单位为秒 int interval() default 60; // 时间段内最大请求次数 int maxCount() default 10; } ``` 然后,在切面中,我们可以拦截该注解标注的方法,并且进行限制调用频率的操作。可以使用ConcurrentHashMap来存储每个接口的调用次数和最后一次调用时间。 ```java @Component @Aspect public class FrequencyLimitAspect { private ConcurrentHashMap<String, Long> lastRequestTimeMap = new ConcurrentHashMap<>(); private ConcurrentHashMap<String, Integer> requestCountMap = new ConcurrentHashMap<>(); @Around("@annotation(frequencyLimit)") public Object frequencyLimit(ProceedingJoinPoint joinPoint, FrequencyLimit frequencyLimit) throws Throwable { Object result = null; String methodName = joinPoint.getSignature().toLongString(); long currentTime = System.currentTimeMillis(); int interval = frequencyLimit.interval(); int maxCount = frequencyLimit.maxCount(); synchronized (this) { // 获取最后一次请求时间和请求次数 Long lastRequestTime = lastRequestTimeMap.get(methodName); Integer requestCount = requestCountMap.get(methodName); if (lastRequestTime == null || currentTime - lastRequestTime >= interval * 1000) { // 如果该接口在限制时间段内没有被调用过,则重置请求次数和最后一次请求时间 lastRequestTimeMap.put(methodName, currentTime); requestCountMap.put(methodName, 1); } else { // 如果该接口在限制时间段内已经被调用过,则增加请求次数 requestCount++; if (requestCount > maxCount) { // 如果请求次数超过了限制,则抛出异常 throw new RuntimeException("Exceeded maximum request limit"); } lastRequestTimeMap.put(methodName, currentTime); requestCountMap.put(methodName, requestCount); } } // 调用原始方法 result = joinPoint.proceed(); return result; } } ``` 在切面中,我们使用synchronized关键字来保证线程安全,因为ConcurrentHashMap并不能完全保证线程安全。同时,我们使用了@Around注解来拦截被@FrequencyLimit注解标注的方法,然后在方法中实现限制调用频率的逻辑。 这样,我们就可以实现接口调用频率限制了。在需要限制调用频率的方法中,我们只需要加上@FrequencyLimit注解即可。例如: ```java @GetMapping("/test") @FrequencyLimit(interval = 60, maxCount = 10) public String test() { return "test"; } ``` 这样,每个IP地址每分钟内最多只能调用该方法10次,超过次数会抛出异常。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

积硅步_成千里

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值