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

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

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

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

记得点赞加收藏哦😁😁😁

1. 注解定义

java 复制代码
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 脚本:

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 封装:

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 切面

java 复制代码
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 使用示例

java 复制代码
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:

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

application.yml 至少得有:

yaml 复制代码
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 保证自增+过期是原子的。

相关推荐
躺平大鹅2 小时前
Java面向对象入门(类与对象,新手秒懂)
java
初次攀爬者2 小时前
RocketMQ在Spring Boot上的基础使用
java·spring boot·rocketmq
花花无缺2 小时前
搞懂@Autowired 与@Resuorce
java·spring boot·后端
Derek_Smart4 小时前
从一次 OOM 事故说起:打造生产级的 JVM 健康检查组件
java·jvm·spring boot
NE_STOP5 小时前
MyBatis-mybatis入门与增删改查
java
孟陬8 小时前
国外技术周刊 #1:Paul Graham 重新分享最受欢迎的文章《创作者的品味》、本周被划线最多 YouTube《如何在 19 分钟内学会 AI》、为何我不
java·前端·后端
想用offer打牌8 小时前
一站式了解四种限流算法
java·后端·go
华仔啊9 小时前
Java 开发千万别给布尔变量加 is 前缀!很容易背锅
java
也些宝9 小时前
Java单例模式:饿汉、懒汉、DCL三种实现及最佳实践
java