怎样通过Redis实现接口限流
基于 Redis + Spring AOP 限流(推荐)
<!– Redis –>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
自定义限流注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RateLimit {
String key() default “”; // 限流的key,可用方法名或自定义
long limit() default 5; // 时间窗口内允许的请求次数
long duration() default 60; // 时间窗口,单位秒
}
限流切面实现
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Aspect
@Component
public class RateLimitAspect {
private final StringRedisTemplate redisTemplate;
public RateLimitAspect(StringRedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
@Around(“@annotation(rateLimit)”)
public Object around(ProceedingJoinPoint joinPoint, RateLimit rateLimit) throws Throwable {
String key = “rate:” + rateLimit.key();
String countStr = redisTemplate.opsForValue().get(key);
long count = countStr == null ? 0 : Long.parseLong(countStr);
if (count >= rateLimit.limit()) {
throw new RuntimeException(“请求过于频繁,请稍后再试”);
}
if (count == 0) {
// 设置过期时间
redisTemplate.opsForValue().set(key, “1”, rateLimit.duration(), TimeUnit.SECONDS);
} else {
redisTemplate.opsForValue().increment(key);
}
return joinPoint.proceed();
}
}
在 Controller 上使用
@RestController
@RequestMapping(“/user”)
public class UserController {
@GetMapping(“/all”)
@RateLimit(key = “allUsers”, limit = 5, duration = 60)
public List<User> getAllUsers() {
return userRepository.findAll();
}
}
效果:
- 每个 key(这里是
"rate:allUsers"
)60 秒内最多访问 5 次。 - 超过就会抛异常,可统一返回前端提示“请求过于频繁”。
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员!
7. 本站有不少源码未能详细测试(解密),不能分辨部分源码是病毒还是误报,所以没有进行任何修改,大家使用前请进行甄别!
66源码网 » 怎样通过Redis实现接口限流