SpringBoot+Redis+Lua防止IP重复防刷攻击

本文介绍了如何利用SpringBoot、Redis和Lua脚本来防止IP重复请求,以防御黑客或恶意用户的防刷攻击。通过限制10秒内同一IP最多访问30次,有效避免系统资源被耗尽。详细阐述了分析过程和具体实现,包括Lua脚本的使用。

SpringBoot+Redis+Lua防止IP重复防刷攻击

分析

黑客或者一些恶意的用户为了攻击网站或者APP,会通过并发用肉机并发或者死循环请求接口,从而导致系统出现宕机。

  • 针对新增数据的接口,会出现大量的重复数据,甚至垃圾数据将数据库和CPU或者内存磁盘耗尽,直到数据库撑爆为止。
  • 针对查询的接口,一般是重点攻击慢查询,比如一个SQL是2s。只要黑客一致攻击,就必然造成系统被拖垮,数据库查询全部被阻塞,连接一直得不到释放造成数据库无法访问。

具体实现

需求:在10秒内,同一IP 127.0.0.1 地址只允许访问30次。

最终效果:

 Long execute = this.stringRedisTemplate.execute(defaultRedisScript, keyList, "30", "10");

分析:keylist = 127.0.0.1 expire 30 incr

  • 分析1:用户ip地址127.0.0.1 访问一次 incr
  • 分析2:用户ip地址127.0.0.1 访问一次 incr
  • 分析3:用户ip地址127.0.0.1 访问一次 incr
  • 分析4:用户ip地址127.0.0.1 访问一次 incr
  • 分析10:用户ip地址127.0.0.1 访问一次 incr

判断当前的次数是否以及达到了10次,如果达到了。就时间当前时间是否已经大于30秒。如果没有大于就不允许访问,否则开始设置过期

新增iplimit.lua文件
-- 为某个接口的请求IP设置计数器,比如:127.0.0.1请求课程接口
-- KEYS[1] = 127.0.0.1 也就是用户的IP
-- ARGV[1] = 过期时间 30m
-- ARGV[2] = 限制的次数
local limitCount = redis.
### Spring Boot 中基于 Redis 和 RateLimit 实现限流切面的示例 以下是完整的代码示例,展示如何在 Spring Boot 应用程序中使用 AOP 和 Redis实现接口限流功能。 #### 1. 添加依赖项 首先,在 `pom.xml` 文件中引入必要的依赖项: ```xml <dependencies> <!-- Spring Boot Starter AOP --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <!-- Spring Data Redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- Lettuce or Jedis as the Redis client --> <dependency> <groupId>io.lettuce.core</groupId> <artifactId>lettuce-core</artifactId> </dependency> </dependencies> ``` --- #### 2. 配置 Redis 参数 在 `application.properties` 或 `application.yml` 文件中配置 Redis 连接参数: ```properties # Redis Configuration spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= spring.redis.timeout=10000ms spring.redis.lettuce.pool.max-active=10 spring.redis.lettuce.pool.max-idle=5 spring.redis.lettuce.pool.min-idle=1 ``` --- #### 3. 创建自定义注解 `@RateLimit` 定义一个注解,用于标记需要限流的接口,并指定限流策略。 ```java import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface RateLimit { int limit(); // 单位时间内允许的最大请求数 long timeWindowInSeconds(); // 时间窗口长度(单位:秒) } ``` --- #### 4. 编写限流服务类 `RateLimiterService` 封装 Redis 操作逻辑,提供限流判断方法。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; @Service public class RateLimiterService { private final StringRedisTemplate redisTemplate; @Autowired public RateLimiterService(StringRedisTemplate redisTemplate) { this.redisTemplate = redisTemplate; } /** * 判断当前请求是否被允许通过限流检查。 * * @param key 请求唯一标识符(如用户ID/IP地址/接口名称等) * @param limit 允许的最大请求数量 * @param duration 时间窗口长度(秒) * @return true 表示允许访问;false 表示已超出限流范围 */ public boolean isAllowed(String key, int limit, long duration) { String value = redisTemplate.opsForValue().get(key); int currentCount = (value != null) ? Integer.parseInt(value) : 0; if (currentCount >= limit) { return false; // 已达到限流上限 } // 更新计数器并设置过期时间 redisTemplate.opsForValue().setIfAbsent(key, "0", duration); // 初始化键值 redisTemplate.opsForValue().increment(key); return true; } } ``` --- #### 5. 创建 AOP 切面类 `RateLimitAspect` 利用 Spring AOP 截获带有 `@RateLimit` 注解的方法,并应用限流逻辑。 ```java import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Aspect @Component public class RateLimitAspect { private static final Logger logger = LoggerFactory.getLogger(RateLimitAspect.class); @Autowired private RateLimiterService rateLimiterService; @Around("@annotation(rateLimit)") public Object handleRateLimit(ProceedingJoinPoint joinPoint, RateLimit rateLimit) throws Throwable { String methodName = joinPoint.getSignature().getName(); String uniqueKey = "rate_limit:" + methodName; // 获取限流参数 int maxRequests = rateLimit.limit(); long windowSizeInSeconds = rateLimit.timeWindowInSeconds(); // 执行限流检查 if (!rateLimiterService.isAllowed(uniqueKey, maxRequests, windowSizeInSeconds)) { logger.warn("Request rejected due to exceeding rate limit: {}", methodName); throw new RuntimeException("Too many requests"); } // 继续执行目标方法 return joinPoint.proceed(); } } ``` --- #### 6. 测试控制器 创建一个简单的 REST 控制器,测试限流效果。 ```java import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @GetMapping("/test") @RateLimit(limit = 5, timeWindowInSeconds = 10) // 每10秒最多允许5次请求 public String testMethod() { return "This method has been accessed successfully!"; } } ``` --- ### 总结 以上代码展示了如何在 Spring Boot 中集成 Redis 和 AOP 技术来实现接口限流功能。核心思路是通过 Redis 记录请求次数,并结合滑动窗口算法动态调整限流状态[^1]。 ```lua -- Lua 脚本用于更高效的限流操作 local key = KEYS[1] local limit = tonumber(ARGV[1]) local increment = tonumber(ARGV[2]) local current = tonumber(redis.call('GET', key) or '0') if current + increment > limit then return 0 -- 达到限流阈值 else redis.call('INCRBY', key, increment) redis.call('EXPIRE', key, ARGV[3]) -- 设置超时时间 return 1 -- 正常请求 end ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

南宫拾壹

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

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

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

打赏作者

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

抵扣说明:

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

余额充值