詳解Springboot分布式限流實(shí)踐
高并發(fā)訪問(wèn)時(shí),緩存、限流、降級(jí)往往是系統(tǒng)的利劍,在互聯(lián)網(wǎng)蓬勃發(fā)展的時(shí)期,經(jīng)常會(huì)面臨因用戶暴漲導(dǎo)致的請(qǐng)求不可用的情況,甚至引發(fā)連鎖反映導(dǎo)致整個(gè)系統(tǒng)崩潰。這個(gè)時(shí)候常見(jiàn)的解決方案之一就是限流了,當(dāng)請(qǐng)求達(dá)到一定的并發(fā)數(shù)或速率,就進(jìn)行等待、排隊(duì)、降級(jí)、拒絕服務(wù)等...
限流算法介紹
a、令牌桶算法
令牌桶算法的原理是系統(tǒng)會(huì)以一個(gè)恒定的速度往桶里放入令牌,而如果請(qǐng)求需要被處理,則需要先從桶里獲取一個(gè)令牌,當(dāng)桶里沒(méi)有令牌可取時(shí),則拒絕服務(wù)。 當(dāng)桶滿時(shí),新添加的令牌被丟棄或拒絕。
b、漏桶算法
其主要目的是控制數(shù)據(jù)注入到網(wǎng)絡(luò)的速率,平滑網(wǎng)絡(luò)上的突發(fā)流量,數(shù)據(jù)可以以任意速度流入到漏桶中。漏桶算法提供了一種機(jī)制,通過(guò)它,突發(fā)流量可以被整形以便為網(wǎng)絡(luò)提供一個(gè)穩(wěn)定的流量。 漏桶可以看作是一個(gè)帶有常量服務(wù)時(shí)間的單服務(wù)器隊(duì)列,如果漏桶為空,則不需要流出水滴,如果漏桶(包緩存)溢出,那么水滴會(huì)被溢出丟棄
c、計(jì)算器限流
計(jì)數(shù)器限流算法是比較常用一種的限流方案也是最為粗暴直接的,主要用來(lái)限制總并發(fā)數(shù),比如數(shù)據(jù)庫(kù)連接池大小、線程池大小、接口訪問(wèn)并發(fā)數(shù)等都是使用計(jì)數(shù)器算法
如:使用AomicInteger
來(lái)進(jìn)行統(tǒng)計(jì)當(dāng)前正在并發(fā)執(zhí)行的次數(shù),如果超過(guò)域值就直接拒絕請(qǐng)求,提示系統(tǒng)繁忙
限流具體代碼實(shí)踐
a、導(dǎo)入依賴(lài)
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</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-data-redis</artifactId> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>21.0</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> </dependencies>
b、屬性配置
在application.properites
資源文件中添加redis
相關(guān)的配置項(xiàng)
spring.redis.host=192.168.68.110 spring.redis.port=6379 spring.redis.password=123456
默認(rèn)情況下spring-boot-data-redis
為我們提供了StringRedisTemplate
但是滿足不了其它類(lèi)型的轉(zhuǎn)換,所以還是得自己去定義其它類(lèi)型的模板
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import java.io.Serializable; /** * redis配置 */ @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Serializable> limitRedisTemplate(LettuceConnectionFactory redisConnectionFactory) { RedisTemplate<String, Serializable> template = new RedisTemplate<>(); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); template.setConnectionFactory(redisConnectionFactory); return template; } }
d、Limit 注解
具體代碼如下
import com.carry.enums.LimitType; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 限流 */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface Limit { /** * 資源的名字 * * @return String */ String name() default ""; /** * 資源的key * * @return String */ String key() default ""; /** * Key的prefix * * @return String */ String prefix() default ""; /** * 給定的時(shí)間段 * 單位秒 * * @return int */ int period(); /** * 最多的訪問(wèn)限制次數(shù) * * @return int */ int count(); /** * 類(lèi)型 * * @return LimitType */ LimitType limitType() default LimitType.CUSTOMER; }
package com.carry.enums; public enum LimitType { /** * 自定義key */ CUSTOMER, /** * 根據(jù)請(qǐng)求者IP */ IP; }
e、Limit 攔截器(AOP)
我們可以通過(guò)編寫(xiě) Lua 腳本實(shí)現(xiàn)自己的API,核心就是調(diào)用execute
方法傳入我們的 Lua 腳本內(nèi)容,然后通過(guò)返回值判斷是否超出我們預(yù)期的范圍,超出則給出錯(cuò)誤提示。
import com.carry.annotation.Limit; import com.carry.enums.LimitType; import com.google.common.collect.ImmutableList; import org.apache.commons.lang3.StringUtils; 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.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.script.DefaultRedisScript; import org.springframework.data.redis.core.script.RedisScript; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.io.Serializable; import java.lang.reflect.Method; @Aspect @Configuration public class LimitInterceptor { private static final Logger logger = LoggerFactory.getLogger(LimitInterceptor.class); private final RedisTemplate<String, Serializable> limitRedisTemplate; @Autowired public LimitInterceptor(RedisTemplate<String, Serializable> limitRedisTemplate) { this.limitRedisTemplate = limitRedisTemplate; } @Around("execution(public * *(..)) && @annotation(com.carry.annotation.Limit)") public Object interceptor(ProceedingJoinPoint pjp) { MethodSignature signature = (MethodSignature) pjp.getSignature(); Method method = signature.getMethod(); Limit limitAnnotation = method.getAnnotation(Limit.class); LimitType limitType = limitAnnotation.limitType(); String name = limitAnnotation.name(); String key; int limitPeriod = limitAnnotation.period(); int limitCount = limitAnnotation.count(); switch (limitType) { case IP: key = getIpAddress(); break; case CUSTOMER: key = limitAnnotation.key(); break; default: key = StringUtils.upperCase(method.getName()); } ImmutableList<String> keys = ImmutableList.of(StringUtils.join(limitAnnotation.prefix(), key)); try { String luaScript = buildLuaScript(); RedisScript<Number> redisScript = new DefaultRedisScript<>(luaScript, Number.class); Number count = limitRedisTemplate.execute(redisScript, keys, limitCount, limitPeriod); logger.info("Access try count is {} for name={} and key = {}", count, name, key); if (count != null && count.intValue() <= limitCount) { return pjp.proceed(); } else { throw new RuntimeException("You have been dragged into the blacklist"); } } catch (Throwable e) { if (e instanceof RuntimeException) { throw new RuntimeException(e.getLocalizedMessage()); } throw new RuntimeException("server exception"); } } /** * 限流 腳本 * * @return lua腳本 */ public String buildLuaScript() { StringBuilder lua = new StringBuilder(); lua.append("local c"); lua.append("\nc = redis.call('get',KEYS[1])"); // 調(diào)用不超過(guò)最大值,則直接返回 lua.append("\nif c and tonumber(c) > tonumber(ARGV[1]) then"); lua.append("\nreturn c;"); lua.append("\nend"); // 執(zhí)行計(jì)算器自加 lua.append("\nc = redis.call('incr',KEYS[1])"); lua.append("\nif tonumber(c) == 1 then"); // 從第一次調(diào)用開(kāi)始限流,設(shè)置對(duì)應(yīng)鍵值的過(guò)期 lua.append("\nredis.call('expire',KEYS[1],ARGV[2])"); lua.append("\nend"); lua.append("\nreturn c;"); return lua.toString(); } private static final String UNKNOWN = "unknown"; /** * 獲取IP地址 * @return */ public String getIpAddress() { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; } }
f、控制層
在接口上添加@Limit()
注解,如下代碼會(huì)在 Redis 中生成過(guò)期時(shí)間為 100s 的 key = test 的記錄,特意定義了一個(gè)AtomicInteger
用作測(cè)試
import com.carry.annotation.Limit; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.concurrent.atomic.AtomicInteger; @RestController public class LimiterController { private static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger(); @Limit(key = "test", period = 100, count = 10, name="resource", prefix = "limit") @GetMapping("/test") public int testLimiter() { // 意味著100S內(nèi)最多可以訪問(wèn)10次 return ATOMIC_INTEGER.incrementAndGet(); } }
注意:上面例子保存在redis中的key值應(yīng)該為“l(fā)imittest”,即@Limit中prefix的值+key的值
測(cè)試
我們?cè)趐ostman中快速訪問(wèn)localhost:8080/test,當(dāng)訪問(wèn)數(shù)超過(guò)10時(shí)出現(xiàn)以下結(jié)果
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
mybatis參數(shù)類(lèi)型不匹配錯(cuò)誤argument type mismatch的處理方案
這篇文章主要介紹了mybatis參數(shù)類(lèi)型不匹配錯(cuò)誤argument type mismatch的處理方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01Spring?Boot集成etcd的詳細(xì)過(guò)程
etcd是一個(gè)分布式鍵值存儲(chǔ)數(shù)據(jù)庫(kù),用于共享配置和服務(wù)發(fā)現(xiàn),etcd采用Go語(yǔ)言編寫(xiě),具有出色的跨平臺(tái)支持,很小的二進(jìn)制文件和強(qiáng)大的社區(qū),這篇文章主要介紹了SpringBoot集成etcd,需要的朋友可以參考下2023-08-08Java零基礎(chǔ)教程之Windows下安裝、啟動(dòng)Tomcat服務(wù)器方法圖解(免安裝版)
這篇文章主要介紹了Windows系統(tǒng)下安裝、啟動(dòng)、注冊(cè)服務(wù)、停止 Tomcat操作的所有方法,本文通過(guò)圖文并茂的方式給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧2016-09-09基于list stream: reduce的使用實(shí)例
這篇文章主要介紹了list stream: reduce的使用實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09Jmeter后置處理器實(shí)現(xiàn)過(guò)程及方法應(yīng)用
這篇文章主要介紹了Jmeter后置處理器實(shí)現(xiàn)過(guò)程及方法應(yīng)用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09淺談java+內(nèi)存分配及變量存儲(chǔ)位置的區(qū)別
下面小編就為大家?guī)?lái)一篇淺談java+內(nèi)存分配及變量存儲(chǔ)位置的區(qū)別。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-08-08