API 接口AOP、Redis限流【固定窗口、滑动窗口、漏桶、令牌桶】
在实现API接口的AOP(面向切面编程)和使用Redis进行限流时,可以使用Spring Boot框架结合Spring Data Redis和AspectJ来实现。以下是使用固定窗口和滑动窗口两种算法的示例代码:
- 引入依赖(Maven示例):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
- 配置Redis:
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
- 实现限流的AOP切面:
@Aspect
@Component
public class RateLimitAspect {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Before("@annotation(rateLimit)")
public void rateLimit(JoinPoint joinPoint, RateLimit rateLimit) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
String key = method.getAnnotation(RateLimit.class).key();
int limit = method.getAnnotation(RateLimit.class).limit();
long windowSize = method.getAnnotation(RateLimit.class).windowSize();
long now = System.currentTimeMillis();
List<Long> timestamps = redisTemplate.opsForList().range(key, 0, -1);
if (timestamps == null) {
timestamps = new ArrayList<>();
}
// 固定窗口限流
if (windowSize > 0) {
while (timestamps.size() > 0 && now - timestamps.get(0) > windowSize) {
timestamps.remove(0);
}
if (timestamps.size() >= limit) {
throw new RuntimeException("Rate limit exceeded");
}
}
// 滑动窗口限流
if (timestamps.size() >= limit) {
throw new RuntimeException("Rate limit exceeded");
}
timestamps.add(now);
redisTemplate.opsForList().trim(key, 0, limit - 1);
redisTemplate.opsForList().rightPush(key, now);
}
}
- 定义注解
RateLimit
:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RateLimit {
评论已关闭