SpringBoot如何實現(xiàn)一個Redis限流注解
更新時間:2025年04月21日 10:15:21 作者:無名指的等待712
這篇文章主要介紹了利用SpringBoot實現(xiàn)一個Redis限流注解方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
SpringBoot實現(xiàn)一個Redis限流注解
使用步驟
1.引入庫
- 代碼如下(示例)
<!-- 引入SpringBoot Aop依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>2.代碼實現(xiàn)
- 添加注解
package com.hhh.springai_test.annotation;
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 RedisLimiting {
int number() default 3;
int time() default 60;
String message() default "請求過于頻繁,請稍后再試";
}- 新增限流AOP實現(xiàn)
package com.hhh.springai_test.aop;
import cn.hutool.crypto.digest.MD5;
import com.hhh.springai_test.annotation.RedisLimiting;
import com.hhh.springai_test.common.ErrorCode;
import com.hhh.springai_test.exception.BusinessException;
import com.hhh.springai_test.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
@Aspect
@Component("redisLimitingAspect")
@Slf4j
public class RedisLimitingAspect {
@Autowired
private RedisUtils redisUtils;
@Around("@annotation(com.hhh.springai_test.annotation.RedisLimiting)") // 只攔截帶 @redisLimiting 的方法
public Object redisLimiting(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod(); // 直接獲取被代理的方法
// 獲取 @redisLimiting 注解
RedisLimiting annotation = method.getAnnotation(RedisLimiting.class);
if (annotation == null) {
return joinPoint.proceed(); // 沒有注解,直接執(zhí)行方法
}
int limit = annotation.number(); // 限制次數(shù)
int expire = annotation.time(); // 過期時間
String message = annotation.message();
log.info("攔截方法: {}, 限流 key: {}, 限流次數(shù): {}, 過期時間: {} 秒",
method.getName(), limit, expire);
// 執(zhí)行限流邏輯
boolean isAllowed = checkRedisLimiting(method, joinPoint.getArgs(), limit, expire);
if (!isAllowed) {
throw new BusinessException(ErrorCode.BUSY_ERROR,message);
}
return joinPoint.proceed(); // 執(zhí)行原方法
}
private boolean checkRedisLimiting(Method method, Object[] args, int limit, int expire) {
// 生成 Redis Key
String redisKey = generateRedisKey(method, args);
// 查詢 Redis 是否存在
Object o = redisUtils.get(redisKey);
if (o == null) {
redisUtils.setex(redisKey, 1, expire); // 初始值設為1,并設置過期時間
return true;
} else {
int count = Integer.parseInt(o.toString());
if (count >= limit) {
return false; // 超過限制
} else {
redisUtils.increment(redisKey, 1); // 遞增計數(shù)
return true;
}
}
}
private String generateRedisKey(Method method, Object[] args) {
StringBuilder builder = new StringBuilder();
builder.append(method.getDeclaringClass().getName()).append(":").append(method.getName()).append(":");
Parameter[] parameters = method.getParameters();
for (int i = 0; i < parameters.length; i++) {
builder.append(parameters[i].getName()).append("=").append(args[i]).append("&");
}
return MD5.create().digestHex16(builder.toString()); // 生成唯一 Redis Key
}
}- 實現(xiàn)代碼的攔截
@GetMapping("/getAllModel")
@RedisLimiting(number = 3, time = 60,message = "不要再請求我的獲取aiModel方法了")
public BaseResponse<List<AiModelVO>> getAllModel() {
return ResultUtils.success(aiModelService.getAllModel());
}總結
以上就是今天要講的內(nèi)容,本文僅僅簡單介紹了pandas的使用,而pandas提供了大量能使我們快速便捷地處理數(shù)據(jù)的函數(shù)和方法。
這些僅為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
使用JMX監(jiān)控Zookeeper狀態(tài)Java API
今天小編就為大家分享一篇關于使用JMX監(jiān)控Zookeeper狀態(tài)Java API,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03
Java導出Excel統(tǒng)計報表合并單元格的方法詳解
我們在日常編程過程中,總是會碰見導出相關表格信息的需求,所以就讓我們一起來學習一下,這篇文章主要給大家介紹了關于Java導出Excel統(tǒng)計報表合并單元格的相關資料,需要的朋友可以參考下2021-10-10
JDBC+GUI實現(xiàn)簡單學生管理系統(tǒng)
這篇文章主要為大家詳細介紹了JDBC+GUI實現(xiàn)簡單學生管理系統(tǒng),具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-02-02

