自定义限流方案(基于 Redis + 注解)

分布式自定义限流方案(基于 Redis + 注解)

下面是一套在分布式环境下可用的“注解限流”实现,核心特点:

  • 使用 @RateLimit 注解到方法上
  • 通过 Spring AOP 拦截
  • 限流规则存到 Redis,所有实例共享
  • 使用 Lua 脚本保证原子性
  • 支持按接口(默认)、自定义 key、IP 维度

记得点赞加收藏哦😁😁😁

1. 注解定义

package com.example.limiter.annotation;

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RateLimit {

    /**
     * 限流的时间窗口,单位:秒
     * 比如 60 就是 60 秒内最多 N 次
     */
    int windowSeconds() default 60;

    /**
     * 时间窗口内允许的最大访问次数
     */
    int maxCount() default 100;

    /**
     * 限流的 key,默认空表示自动生成(类名#方法名)
     * 可以写上 "#ip" 表示按 IP 限流(在切面里处理)
     */
    String key() default "";

    /**
     * 是否按 IP 维度限流
     */
    boolean perIp() default false;
}

2. Redis 限流服务

使用 Lua 做“滑动窗口/固定窗口计数”都行,这里给一个简单固定窗口计数版:key = prefix + windowStart,在窗口期内自增,超过就限。

Lua 脚本:

-- KEYS[1] 限流key
-- ARGV[1] 窗口过期时间(秒)
-- ARGV[2] 最大次数
local current = redis.call("INCR", KEYS[1])
if tonumber(current) == 1 then
    redis.call("EXPIRE", KEYS[1], tonumber(ARGV[1]))
end
if tonumber(current) > tonumber(ARGV[2]) then
    return 0
end
return 1

Java 封装:

package com.example.limiter.core;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;

@Component
public class RedisRateLimiter {

    private static final String SCRIPT =
            "local current = redis.call('INCR', KEYS[1]) " +
            "if tonumber(current) == 1 then " +
            "  redis.call('EXPIRE', KEYS[1], tonumber(ARGV[1])) " +
            "end " +
            "if tonumber(current) > tonumber(ARGV[2]) then " +
            "  return 0 " +
            "end " +
            "return 1 ";

    private final StringRedisTemplate stringRedisTemplate;
    private final DefaultRedisScript<Long> redisScript;

    public RedisRateLimiter(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.redisScript = new DefaultRedisScript<>();
        this.redisScript.setScriptText(SCRIPT);
        this.redisScript.setResultType(Long.class);
    }

    /**
     * @param key redis限流key
     * @param windowSeconds 窗口秒数
     * @param maxCount 窗口内最大次数
     * @return true 表示允许
     */
    public boolean allowRequest(String key, int windowSeconds, int maxCount) {
        Long res = stringRedisTemplate.execute(
                redisScript,
                Collections.singletonList(key),
                String.valueOf(windowSeconds),
                String.valueOf(maxCount)
        );
        return res != null && res == 1L;
    }
}

3. AOP 切面

package com.example.limiter.aop;

import com.example.limiter.annotation.RateLimit;
import com.example.limiter.core.RedisRateLimiter;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;

@Aspect
@Component
public class RateLimitAspect {

    private final RedisRateLimiter redisRateLimiter;

    public RateLimitAspect(RedisRateLimiter redisRateLimiter) {
        this.redisRateLimiter = redisRateLimiter;
    }

    @Before("@annotation(com.example.limiter.annotation.RateLimit)")
    public void doBefore(JoinPoint joinPoint) {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        RateLimit rateLimit = method.getAnnotation(RateLimit.class);

        String baseKey = rateLimit.key();
        if (baseKey == null || baseKey.isEmpty()) {
            // 默认用 类名#方法名
            baseKey = joinPoint.getTarget().getClass().getName() + "#" + method.getName();
        }

        // 是否按IP限流
        if (rateLimit.perIp()) {
            HttpServletRequest request = currentRequest();
            if (request != null) {
                String ip = getClientIp(request);
                baseKey = baseKey + ":ip:" + ip;
            }
        }

        // 拼上时间窗口粒度可以更细,但这里用脚本里的expire就够了
        boolean allowed = redisRateLimiter.allowRequest(
                "rate:limit:" + baseKey,
                rateLimit.windowSeconds(),
                rateLimit.maxCount()
        );

        if (!allowed) {
            // 超过阈值,抛异常或返回特定错误
            throw new RuntimeException("Too many requests, please try later.");
        }
    }

    private HttpServletRequest currentRequest() {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attrs == null ? null : attrs.getRequest();
    }

    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
            // 多级代理取第一个
            return ip.split(",")[0];
        }
        ip = request.getHeader("X-Real-IP");
        if (ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }
}

4. Controller 使用示例

import com.example.limiter.annotation.RateLimit;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {

    // 60秒内最多10次
    @RateLimit(windowSeconds = 60, maxCount = 10)
    @GetMapping("/demo")
    public String demo() {
        return "ok";
    }

    // 针对IP限流
    @RateLimit(windowSeconds = 60, maxCount = 5, perIp = true)
    @GetMapping("/ip-demo")
    public String ipDemo() {
        return "ok";
    }

    // 自定义key(比如按业务维度)
    @RateLimit(windowSeconds = 10, maxCount = 3, key = "sendSms")
    @GetMapping("/send-sms")
    public String sms() {
        return "sms ok";
    }
}

5. 依赖说明

需要 Spring Data Redis:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

application.yml 至少得有:

spring:
  data:
    redis:
      host: localhost
      port: 6379

6. 思路扩展

  1. 滑动窗口:现在是固定窗口计数,足够大部分接口。如果想更平滑,可以把 Lua 换成 zset 写法。
  2. 返回码:上面直接抛 RuntimeException,你可以换成自定义业务异常,ControllerAdvice 统一返回 429。
  3. 多规则:可以在注解里加枚举,比如 type=LIMIT_IPLIMIT_USER,切面里不同拼 key 即可。
  4. 限流配置中心:如果你不想写死注解里的值,可以在切面里先查一把 Redis/DB 的限流配置,查不到再用注解默认值。

这样这一套就是分布式可用的注解限流了,核心就是:所有实例都去 Redis 抢同一个 key 的次数,再加 Lua 保证自增+过期是原子的。

### 如何使用 Redis 实现自定义注解进行接口限流 #### 准备工作 为了实现基于Redis的接口限流,需先完成必要的环境准备。这包括引入所需的依赖库并配置好Redis连接池。 ```xml <!-- Maven Dependency --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.redisson</groupId> <artifactId>redisson-spring-boot-starter</artifactId> </dependency> ``` #### 创建限流注解 定义一个名为`@RateLimit`的自定义注解用于标记需要限流的方法或类[^1]。 ```java import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ ElementType.METHOD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) public @interface RateLimit { int limit() default 100; // 默认每分钟最多允许访问次数 String keyPrefix() default "rate_limit:"; // redis键前缀 } ``` #### 定制 `RedisTemplate` 为了让后续操作更加便捷高效,建议对默认提供的`RedisTemplate`做适当扩展,以便更好地支持限流逻辑中的原子性计数需求[^3]。 ```java @Configuration public class CustomRedisConfig { @Bean public RedisTemplate<String, Object> customRedisTemplate(LettuceConnectionFactory connectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); Jackson2JsonRedisSerializer<Object> jacksonSer = new Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jacksonSer.setObjectMapper(om); template.setValueSerializer(jacksonSer); template.afterPropertiesSet(); return template; } } ``` #### 开发 Lua 脚本 编写一段Lua脚本来执行限流判断逻辑,并将其注册到Spring上下文中供后续调用[^4]。 ```lua -- lua script for rate limiting local function tryAcquire(key, maxCount, timeWindowInSeconds) local currentTimestamp = tonumber(redis.call('time')[1]) -- Remove expired entries from sorted set redis.call("ZREMRANGEBYSCORE", key, 0, currentTimestamp - timeWindowInSeconds) -- Get the number of elements within the specified window local count = tonumber(redis.call("ZCARD", key)) if count >= maxCount then return false end -- Add a new entry with timestamp as score redis.call("ZADD", key, currentTimestamp, currentTimestamp) redis.call("EXPIRE", key, timeWindowInSeconds) return true end return tryAcquire(KEYS[1], ARGV[1], ARGV[2]) ``` #### 解析注解与应用 AOP 切面 通过AOP切面对标注有`@RateLimit`的目标方法实施环绕通知,在实际调用之前检查当前请求是否满足速率限制条件[^2]。 ```java @Aspect @Component @Slf4j public class RateLimiterAspect { private final RedissonClient redissonClient; public RateLimiterAspect(RedissonClient redissonClient){ this.redissonClient=redissonClient; } @Around("@annotation(rateLimit)") public Object around(ProceedingJoinPoint joinPoint,@Annotation RateLimit rateLimit)throws Throwable{ MethodSignature signature=(MethodSignature)joinPoint.getSignature(); Class<?> targetClass=signature.getMethod().getDeclaringClass(); String methodName=signature.getName(); RScript script=this.redissonClient.getScript(); List<Object> args=Collections.singletonList(joinPoint.getArgs()); String uniqueKey=rateLimit.keyPrefix()+targetClass.getSimpleName()+"."+methodName+"_"+args.hashCode(); Boolean result=(Boolean)script.eval( RScript.Mode.READ_WRITE, getLuaScript(), RScript.ReturnType.BOOLEAN, Collections.singletonList(uniqueKey), Arrays.asList(String.valueOf(rateLimit.limit()),String.valueOf(60)) ); if(!result){ throw new TooManyRequestsException("Too many requests"); } return joinPoint.proceed(); } private static String getLuaScript(){ StringBuilder sb=new StringBuilder(); // ... (insert your Lua code here) return sb.toString(); } } ``` #### 自定义异常处理 当超过设定阈值时抛出自定义异常告知客户端已达到最大访问频率。 ```java @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(value = TooManyRequestsException.class) public ResponseEntity handleTooManyRequestExceptions(Exception e){ log.error(e.getMessage(),e); return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).body(new ErrorResult("Error","You have exceeded maximum allowed request frequency")); } } class ErrorResult { private String status; private String message; public ErrorResult(String status, String message) { this.status=status; this.message=message; } // getters and setters... } ``` #### 测试结果验证 最后一步是对整个流程进行全面的功能性和压力测试,确保方案能够稳定运行并且具备良好的性能表现。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值