帮我写一个springboot接口防刷的切面
时间: 2023-02-13 14:46:38 浏览: 60
好的,我可以帮你写一个 Spring Boot 接口防刷的切面。
首先,你需要在你的 Spring Boot 应用中引入 AspectJ 的依赖。在你的 pom.xml 文件中添加以下依赖:
```
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
```
然后,你可以创建一个切面类,用来处理所有的接口请求:
```
@Aspect
@Component
public class RequestLimitAspect {
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Pointcut("@annotation(com.example.annotation.RequestLimit)")
public void requestLimit() {}
@Before("requestLimit()")
public void requestLimit(JoinPoint joinPoint) {
// 获取注解信息
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
RequestLimit requestLimit = method.getAnnotation(RequestLimit.class);
int limit = requestLimit.limit();
int seconds = requestLimit.seconds();
// 获取请求的 IP 地址
String ip = getIpAddress();
// 生成 redis key
String key = "request_limit:" + ip + ":" + method.getName();
// 获取 redis 中存储的计数器
String value = redisTemplate.opsForValue().get(key);
int count = 0;
if (value != null) {
count = Integer.parseInt(value);
}
// 如果计数器大于限制,则抛出异常
if (count > limit) {
throw new RequestLimitException("请求次数超过限制");
}
// 如果计数器不存在,则初始化计数器并设置过期时间
if (value == null) {
redisTemplate.opsForValue().set(key, "1", seconds, TimeUnit.SECONDS);
} else {
// 如果计数器存在,则增加计数