使用SpringBoot?+?Redis?實現(xiàn)接口限流的方式
Redis 除了做緩存,還能干很多很多事情:分布式鎖、限流、處理請求接口冪等性。。。太多太多了
配置
首先我們創(chuàng)建一個 Spring Boot 工程,引入 Web 和 Redis 依賴,同時考慮到接口限流一般是通過注解來標(biāo)記,而注解是通過 AOP 來解析的,所以我們還需要加上 AOP 的依賴,最終的依賴如下:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
然后提前準(zhǔn)備好一個 Redis 實例,這里我們項目配置好之后,直接配置一下 Redis 的基本信息即可,如下:
spring.redis.host=localhost spring.redis.port=6379 spring.redis.password=123
限流注解
接下來我們創(chuàng)建一個限流注解,我們將限流分為兩種情況:
- 針對當(dāng)前接口的全局性限流,例如該接口可以在 1 分鐘內(nèi)訪問 100 次。
- 針對某一個 IP 地址的限流,例如某個 IP 地址可以在 1 分鐘內(nèi)訪問 100 次。
針對這兩種情況,我們創(chuàng)建一個枚舉類:
public enum LimitType { /** * 默認策略全局限流 */ DEFAULT, /** * 根據(jù)請求者IP進行限流 */ IP }
接下來我們來創(chuàng)建限流注解:
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface RateLimiter { /** * 限流key */ String key() default "rate_limit:"; /** * 限流時間,單位秒 */ int time() default 60; /** * 限流次數(shù) */ int count() default 100; /** * 限流類型 */ LimitType limitType() default LimitType.DEFAULT; }
第一個參數(shù)限流的 key,這個僅僅是一個前綴,將來完整的 key 是這個前綴再加上接口方法的完整路徑,共同組成限流 key,這個 key 將被存入到 Redis 中。
另外三個參數(shù)好理解,我就不多說了。
好了,將來哪個接口需要限流,就在哪個接口上添加 @RateLimiter
注解,然后配置相關(guān)參數(shù)即可。
定制 RedisTemplate
在 Spring Boot 中,我們其實更習(xí)慣使用 Spring Data Redis 來操作 Redis,不過默認的 RedisTemplate 有一個小坑,就是序列化用的是 JdkSerializationRedisSerializer,不知道小伙伴們有沒有注意過,直接用這個序列化工具將來存到 Redis 上的 key 和 value 都會莫名其妙多一些前綴,這就導(dǎo)致你用命令讀取的時候可能會出錯。
例如存儲的時候,key 是 name,value 是 test,但是當(dāng)你在命令行操作的時候,get name
卻獲取不到你想要的數(shù)據(jù),原因就是存到 redis 之后 name 前面多了一些字符,此時只能繼續(xù)使用 RedisTemplate 將之讀取出來。
我們用 Redis 做限流會用到 Lua 腳本,使用 Lua 腳本的時候,就會出現(xiàn)上面說的這種情況,所以我們需要修改 RedisTemplate 的序列化方案。
可能有小伙伴會說為什么不用 StringRedisTemplate 呢?StringRedisTemplate 確實不存在上面所說的問題,但是它能夠存儲的數(shù)據(jù)類型不夠豐富,所以這里不考慮。
修改 RedisTemplate 序列化方案,代碼如下:
@Configuration public class RedisConfig { @Bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(connectionFactory); // 使用Jackson2JsonRedisSerialize 替換默認序列化(默認采用的是JDK序列化) Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); redisTemplate.setKeySerializer(jackson2JsonRedisSerializer); redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); redisTemplate.setHashKeySerializer(jackson2JsonRedisSerializer); redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); return redisTemplate; } }
這個其實也沒啥好說的,key 和 value 我們都使用 Spring Boot 中默認的 jackson 序列化方式來解決。
Lua 腳本
這個其實我在之前 vhr 那一套視頻中講過,Redis 中的一些原子操作我們可以借助 Lua 腳本來實現(xiàn),想要調(diào)用 Lua 腳本,我們有兩種不同的思路:
- 在 Redis 服務(wù)端定義好 Lua 腳本,然后計算出來一個散列值,在 Java 代碼中,通過這個散列值鎖定要執(zhí)行哪個 Lua 腳本。
- 直接在 Java 代碼中將 Lua 腳本定義好,然后發(fā)送到 Redis 服務(wù)端去執(zhí)行。
Spring Data Redis 中也提供了操作 Lua 腳本的接口,還是比較方便的,所以我們這里就采用第二種方案。
我們在 resources 目錄下新建 lua 文件夾專門用來存放 lua 腳本,腳本內(nèi)容如下:
local key = KEYS[1] local count = tonumber(ARGV[1]) local time = tonumber(ARGV[2]) local current = redis.call('get', key) if current and tonumber(current) > count then return tonumber(current) end current = redis.call('incr', key) if tonumber(current) == 1 then redis.call('expire', key, time) end return tonumber(current)
這個腳本其實不難,大概瞅一眼就知道干啥用的。KEYS 和 ARGV 都是一會調(diào)用時候傳進來的參數(shù),tonumber 就是把字符串轉(zhuǎn)為數(shù)字,redis.call 就是執(zhí)行具體的 redis 指令,具體流程是這樣:
- 首先獲取到傳進來的 key 以及 限流的 count 和時間 time。
- 通過 get 獲取到這個 key 對應(yīng)的值,這個值就是當(dāng)前時間窗內(nèi)這個接口可以訪問多少次。
- 如果是第一次訪問,此時拿到的結(jié)果為 nil,否則拿到的結(jié)果應(yīng)該是一個數(shù)字,所以接下來就判斷,如果拿到的結(jié)果是一個數(shù)字,并且這個數(shù)字還大于 count,那就說明已經(jīng)超過流量限制了,那么直接返回查詢的結(jié)果即可。
- 如果拿到的結(jié)果為 nil,說明是第一次訪問,此時就給當(dāng)前 key 自增 1,然后設(shè)置一個過期時間。
- 最后把自增 1 后的值返回就可以了。
其實這段 Lua 腳本很好理解。
接下來我們在一個 Bean 中來加載這段 Lua 腳本,如下:
@Bean public DefaultRedisScript<Long> limitScript() { DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(); redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/limit.lua"))); redisScript.setResultType(Long.class); return redisScript; }
可以啦,我們的 Lua 腳本現(xiàn)在就準(zhǔn)備好了。
注解解析
接下來我們就需要自定義切面,來解析這個注解了,我們來看看切面的定義:
@Aspect @Component public class RateLimiterAspect { private static final Logger log = LoggerFactory.getLogger(RateLimiterAspect.class); @Autowired private RedisTemplate<Object, Object> redisTemplate; @Autowired private RedisScript<Long> limitScript; @Before("@annotation(rateLimiter)") public void doBefore(JoinPoint point, RateLimiter rateLimiter) throws Throwable { String key = rateLimiter.key(); int time = rateLimiter.time(); int count = rateLimiter.count(); String combineKey = getCombineKey(rateLimiter, point); List<Object> keys = Collections.singletonList(combineKey); try { Long number = redisTemplate.execute(limitScript, keys, count, time); if (number==null || number.intValue() > count) { throw new ServiceException("訪問過于頻繁,請稍候再試"); } log.info("限制請求'{}',當(dāng)前請求'{}',緩存key'{}'", count, number.intValue(), key); } catch (ServiceException e) { throw e; } catch (Exception e) { throw new RuntimeException("服務(wù)器限流異常,請稍候再試"); } } public String getCombineKey(RateLimiter rateLimiter, JoinPoint point) { StringBuffer stringBuffer = new StringBuffer(rateLimiter.key()); if (rateLimiter.limitType() == LimitType.IP) { stringBuffer.append(IpUtils.getIpAddr(((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest())).append("-"); } MethodSignature signature = (MethodSignature) point.getSignature(); Method method = signature.getMethod(); Class<?> targetClass = method.getDeclaringClass(); stringBuffer.append(targetClass.getName()).append("-").append(method.getName()); return stringBuffer.toString(); } }
這個切面就是攔截所有加了 @RateLimiter
注解的方法,在前置通知中對注解進行處理。
- 首先獲取到注解中的 key、time 以及 count 三個參數(shù)。
- 獲取一個組合的 key,所謂的組合的 key,就是在注解的 key 屬性基礎(chǔ)上,再加上方法的完整路徑,如果是 IP 模式的話,就再加上 IP 地址。以 IP 模式為例,最終生成的 key 類似這樣:
rate_limit:127.0.0.1-org.javaboy.ratelimiter.controller.HelloController-hello
(如果不是 IP 模式,那么生成的 key 中就不包含 IP 地址)。 - 將生成的 key 放到集合中。
- 通過 redisTemplate.execute 方法取執(zhí)行一個 Lua 腳本,第一個參數(shù)是腳本所封裝的對象,第二個參數(shù)是 key,對應(yīng)了腳本中的 KEYS,后面是可變長度的參數(shù),對應(yīng)了腳本中的 ARGV。
- 將 Lua 腳本執(zhí)行的結(jié)果與 count 進行比較,如果大于 count,就說明過載了,拋異常就行了。
接口測試
接下來我們就進行接口的一個簡單測試,如下:
@RestController public class HelloController { @GetMapping("/hello") @RateLimiter(time = 5,count = 3,limitType = LimitType.IP) public String hello() { return "hello>>>"+new Date(); } }
每一個 IP 地址,在 5 秒內(nèi)只能訪問 3 次。
這個自己手動刷新瀏覽器都能測試出來。
全局異常處理
由于過載的時候是拋異常出來,所以我們還需要一個全局異常處理器,如下:
@RestControllerAdvice public class GlobalException { @ExceptionHandler(ServiceException.class) public Map<String,Object> serviceException(ServiceException e) { HashMap<String, Object> map = new HashMap<>(); map.put("status", 500); map.put("message", e.getMessage()); return map; } }
這是一個小 demo,我就不去定義實體類了,直接用 Map 來返回 JSON 了。 最后我們看看過載時的測試效果:
好啦,這就是我們使用 Redis 做限流的方式。
到此這篇關(guān)于SpringBoot + Redis 實現(xiàn)接口限流的文章就介紹到這了,更多相關(guān)SpringBoot Redis 接口限流內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Springboot+Redis實現(xiàn)API接口防刷限流的項目實踐
- SpringBoot整合Redis并且用Redis實現(xiàn)限流的方法 附Redis解壓包
- 基于SpringBoot+Redis實現(xiàn)一個簡單的限流器
- SpringBoot使用Redis對用戶IP進行接口限流的項目實踐
- SpringBoot使用Redis對用戶IP進行接口限流的示例詳解
- SpringBoot Redis用注釋實現(xiàn)接口限流詳解
- SpringBoot中使用Redis對接口進行限流的實現(xiàn)
- springboot+redis 實現(xiàn)分布式限流令牌桶的示例代碼
- SpringBoot整合redis實現(xiàn)計數(shù)器限流的示例
相關(guān)文章
nestjs使用redis實現(xiàn)ip限流的步驟詳解
如果使用nestjs開發(fā)接口并部署之后,我們通常需要考慮到接口是否會被惡意盜刷消耗過多的資源,一個簡單的方式就是限制在單位時間內(nèi)的訪問次數(shù),所以本文給大家介紹了nestjs使用redis實現(xiàn)ip限流的步驟,需要的朋友可以參考下2025-01-01Redis中的配置文件,數(shù)據(jù)持久化,事務(wù)
這篇文章主要介紹了Redis中的配置文件,數(shù)據(jù)持久化,事務(wù)問題,具有很好的參考價值,希望對大家有所幫助。2022-12-12