巧妙运用Redisson打造自定义限流注解,让接口防刷更高效
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
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)
@interface RateLimiter {
int limit() default 5;
}
@Component
public class RateLimiterAspect {
@Autowired
private RedissonClient redissonClient;
public Object around(ProceedingJoinPoint joinPoint, RateLimiter rateLimiter) throws Throwable {
String key = "rate_limiter:" + joinPoint.getSignature().toShortString();
try (RRateLimiter rateLimiter = redissonClient.getRateLimiter(key)) {
if (rateLimiter.tryAcquire(rateLimiter.getPermissionLimit(), rateLimiter.getTimeout(), rateLimiter.getUnit())) {
return joinPoint.proceed();
} else {
throw new RuntimeException("Rate limit exceeded");
}
}
}
}
这个示例代码定义了一个自定义注解RateLimiter
和一个切面RateLimiterAspect
,使用Redisson的RRateLimiter
对象来实现限流功能。切面中的around
方法使用注解来限制方法的访问频率。如果尝试超过限制,则抛出异常。这种方式提高了接口的安全性,也使得代码更加清晰易懂。
评论已关闭