自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

我司用了 6 年的 Redis 分布式限流器,可以說是非常厲害了

新聞 開發(fā)工具 分布式 Redis
由于互聯(lián)網(wǎng)公司的流量巨大,系統(tǒng)上線會做一個流量峰值的評估,尤其是像各種秒殺促銷活動,為了保證系統(tǒng)不被巨大的流量壓垮,會在系統(tǒng)流量到達一定閾值時,拒絕掉一部分流量。

 一、什么是限流?為什么要限流?

不知道大家有沒有做過帝都的地鐵,就是進地鐵站都要排隊的那種,為什么要這樣擺長龍轉(zhuǎn)圈圈?答案就是為了 限流 !因為一趟地鐵的運力是有限的,一下擠進去太多人會造成站臺的擁擠、列車的超載,存在一定的安全隱患。同理,我們的程序也是一樣,它處理請求的能力也是有限的,一旦請求多到超出它的處理極限就會崩潰。為了不出現(xiàn)最壞的崩潰情況,只能耽誤一下大家進站的時間。限流是保證系統(tǒng)高可用的重要手段?。?!

[[324330]]

由于互聯(lián)網(wǎng)公司的流量巨大,系統(tǒng)上線會做一個流量峰值的評估,尤其是像各種秒殺促銷活動,為了保證系統(tǒng)不被巨大的流量壓垮,會在系統(tǒng)流量到達一定閾值時,拒絕掉一部分流量。

限流會導致用戶在短時間內(nèi)(這個時間段是毫秒級的)系統(tǒng)不可用,一般我們衡量系統(tǒng)處理能力的指標是每秒的 QPS 或者 TPS ,假設(shè)系統(tǒng)每秒的流量閾值是1000,理論上一秒內(nèi)有第1001個請求進來時,那么這個請求就會被限流。

二、限流方案

1、計數(shù)器
Java內(nèi)部也可以通過原子類計數(shù)器 AtomicInteger 、 Semaphore 信號量來做簡單的限流。

  1. // 限流的個數(shù) 
  2. private int maxCount = 10
  3. // 指定的時間內(nèi) 
  4. private long interval = 60
  5. // 原子類計數(shù)器 
  6. private AtomicInteger atomicInteger = new AtomicInteger(0); 
  7. // 起始時間 
  8. private long startTime = System.currentTimeMillis(); 
  9.  
  10. public boolean limit(int maxCount, int interval) { 
  11. atomicInteger.addAndGet(1); 
  12. if (atomicInteger.get() == 1) { 
  13. startTime = System.currentTimeMillis(); 
  14. atomicInteger.addAndGet(1); 
  15. return true
  16. // 超過了間隔時間,直接重新開始計數(shù) 
  17. if (System.currentTimeMillis() - startTime > interval * 1000) { 
  18. startTime = System.currentTimeMillis(); 
  19. atomicInteger.set(1); 
  20. return true
  21. // 還在間隔時間內(nèi),check有沒有超過限流的個數(shù) 
  22. if (atomicInteger.get() > maxCount) { 
  23. return false
  24. return true

2、漏桶算法

漏桶算法思路很簡單,我們把水比作是 請求 ,漏桶比作是 系統(tǒng)處理能力極限 ,水先進入到漏桶里,漏桶里的水按一定速率流出,當流出的速率小于流入的速率時,由于漏桶容量有限,后續(xù)進入的水直接溢出(拒絕請求),以此實現(xiàn)限流。

3、令牌桶算法

令牌桶算法的原理也比較簡單,我們可以理解成醫(yī)院的掛號看病,只有拿到號以后才可以進行診病。

系統(tǒng)會維護一個令牌( token )桶,以一個恒定的速度往桶里放入令牌( token ),這時如果有請求進來想要被處理,則需要先從桶里獲取一個令牌( token ),當桶里沒有令牌( token)可取時,則該請求將被拒絕服務。令牌桶算法通過控制桶的容量、發(fā)放令牌的速率,來達到對請求的限制。

4、Redis + Lua

很多同學不知道 Lua 是啥?個人理解, Lua 腳本和 MySQL 數(shù)據(jù)庫的存儲過程比較相似,他們執(zhí)行一組命令,所有命令的執(zhí)行要么全部成功或者失敗,以此達到原子性。也可以把 Lua 腳本理解為,一段具有業(yè)務邏輯的代碼塊。

而 Lua 本身就是一種編程語言,雖然 redis 官方?jīng)]有直接提供限流相應的 API ,但卻支持了Lua 腳本的功能,可以使用它實現(xiàn)復雜的令牌桶或漏桶算法,也是分布式系統(tǒng)中實現(xiàn)限流的主要方式之一。

相比 Redis 事務, Lua腳本 的優(yōu)點:

  1. 減少網(wǎng)絡開銷:使用 Lua 腳本,無需向 Redis 發(fā)送多次請求,執(zhí)行一次即可,減少網(wǎng)絡傳輸
  2. 原子操作: Redis 將整個 Lua 腳本作為一個命令執(zhí)行,原子,無需擔心并發(fā)
  3. 復用: Lua 腳本一旦執(zhí)行,會永久保存 Redis 中,,其他客戶端可復用

Lua 腳本大致邏輯如下:

  1. -- 獲取調(diào)用腳本時傳入的第一個key值(用作限流的 key) 
  2. local key = KEYS[1
  3. -- 獲取調(diào)用腳本時傳入的第一個參數(shù)值(限流大?。?nbsp;
  4. local limit = tonumber(ARGV[1]) 
  5.  
  6. -- 獲取當前流量大小 
  7. local curentLimit = tonumber(redis.call('get', key) or "0"
  8.  
  9. -- 是否超出限流 
  10. if curentLimit + 1 > limit then 
  11. -- 返回(拒絕) 
  12. return 0 
  13. else 
  14. -- 沒有超出 value + 1 
  15. redis.call("INCRBY", key, 1
  16. -- 設(shè)置過期時間 
  17. redis.call("EXPIRE", key, 2
  18. -- 返回(放行) 
  19. return 1 
  20. end 
  • 通過 KEYS[1] 獲取傳入的key參數(shù)
  • 通過 ARGV[1] 獲取傳入的 limit 參數(shù)
  • redis.call方法,從緩存中g(shù)et和key相關(guān)的值,如果為null那么就返回0
  • 接著判斷緩存中記錄的數(shù)值是否會大于限制大小,如果超出表示該被限流,返回0
  • 如果未超過,那么該key的緩存值+1,并設(shè)置過期時間為1秒鐘以后,并返回緩存值+1

這種方式是本文推薦的方案,具體實現(xiàn)會在后邊做細說。

5、網(wǎng)關(guān)層限流

限流常在網(wǎng)關(guān)這一層做,比如 Nginx 、 Openresty 、 kong 、 zuul 、 Spring Cloud Gateway 等,而像 spring cloud - gateway 網(wǎng)關(guān)限流底層實現(xiàn)原理,就是基于 Redis + Lua ,通過內(nèi)置 Lua 限流腳本的方式。

三、Redis + Lua 限流實現(xiàn)

下面我們通過 自定義注解 、 aop 、 Redis + Lua 實現(xiàn)限流,步驟會比較詳細,為了小白能讓快速上手這里啰嗦一點,有經(jīng)驗的老鳥們多擔待一下。

1、環(huán)境準備

springboot 項目創(chuàng)建地址:https://start.spring.io,很方便實用的一個工具。

2、引入依賴包

pom文件中添加如下依賴包,比較關(guān)鍵的就是 spring-boot-starter-data-redis 和 spring-boot-starter-aop 。

  1. <dependencies> 
  2.       <dependency> 
  3.           <groupId>org.springframework.boot</groupId> 
  4.           <artifactId>spring-boot-starter-web</artifactId> 
  5.       </dependency> 
  6.       <dependency> 
  7.           <groupId>org.springframework.boot</groupId> 
  8.           <artifactId>spring-boot-starter-data-redis</artifactId> 
  9.       </dependency> 
  10.       <dependency> 
  11.           <groupId>org.springframework.boot</groupId> 
  12.           <artifactId>spring-boot-starter-aop</artifactId> 
  13.       </dependency> 
  14.       <dependency> 
  15.           <groupId>com.google.guava</groupId> 
  16.           <artifactId>guava</artifactId> 
  17.           <version>21.0</version> 
  18.       </dependency> 
  19.       <dependency> 
  20.           <groupId>org.springframework.boot</groupId> 
  21.           <artifactId>spring-boot-starter-test</artifactId> 
  22.       </dependency> 
  23.       <dependency> 
  24.           <groupId>org.apache.commons</groupId> 
  25.           <artifactId>commons-lang3</artifactId> 
  26.       </dependency> 
  27.  
  28.       <dependency> 
  29.           <groupId>org.springframework.boot</groupId> 
  30.           <artifactId>spring-boot-starter-test</artifactId> 
  31.           <scope>test</scope> 
  32.           <exclusions> 
  33.               <exclusion> 
  34.                   <groupId>org.junit.vintage</groupId> 
  35.                   <artifactId>junit-vintage-engine</artifactId> 
  36.               </exclusion> 
  37.           </exclusions> 
  38.       </dependency> 
  39.   </dependencies> 

3、配置application.properties

在 application.properties 文件中配置提前搭建好的 redis 服務地址和端口。

  1. spring.redis.host=127.0.0.1 
  2.  
  3. spring.redis.port=6379 

4、配置RedisTemplate實例

  1. @Configuration 
  2. public class RedisLimiterHelper { 
  3.  
  4.     @Bean 
  5.     public RedisTemplate<String, Serializable> limitRedisTemplate(LettuceConnectionFactory redisConnectionFactory) { 
  6.         RedisTemplate<String, Serializable> template = new RedisTemplate<>(); 
  7.         template.setKeySerializer(new StringRedisSerializer()); 
  8.         template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); 
  9.         template.setConnectionFactory(redisConnectionFactory); 
  10.         return template; 
  11.     } 

限流類型枚舉類

  1. /** 
  2.  * @author fu 
  3.  * @description 限流類型 
  4.  * @date 2020/4/8 13:47 
  5.  */ 
  6. public enum LimitType { 
  7.  
  8.     /** 
  9.      * 自定義key 
  10.      */ 
  11.     CUSTOMER, 
  12.  
  13.     /** 
  14.      * 請求者IP 
  15.      */ 
  16.     IP; 

5、自定義注解

我們自定義個 @Limit 注解,注解類型為 ElementType.METHOD 即作用于方法上。

period 表示請求限制時間段, count 表示在 period 這個時間段內(nèi)允許放行請求的次數(shù)。 limitType 代表限流的類型,可以根據(jù) 請求的IP 、 自定義key ,如果不傳 limitType 屬性則默認用方法名作為默認key。

  1. /** 
  2.  * @author fu 
  3.  * @description 自定義限流注解 
  4.  * @date 2020/4/8 13:15 
  5.  */ 
  6. @Target({ElementType.METHOD, ElementType.TYPE}) 
  7. @Retention(RetentionPolicy.RUNTIME) 
  8. @Inherited 
  9. @Documented 
  10. public @interface Limit { 
  11.  
  12.     /** 
  13.      * 名字 
  14.      */ 
  15.     String name() default ""
  16.  
  17.     /** 
  18.      * key 
  19.      */ 
  20.     String key() default ""
  21.  
  22.     /** 
  23.      * Key的前綴 
  24.      */ 
  25.     String prefix() default ""
  26.  
  27.     /** 
  28.      * 給定的時間范圍 單位(秒) 
  29.      */ 
  30.     int period(); 
  31.  
  32.     /** 
  33.      * 一定時間內(nèi)最多訪問次數(shù) 
  34.      */ 
  35.     int count(); 
  36.  
  37.     /** 
  38.      * 限流的類型(用戶自定義key 或者 請求ip) 
  39.      */ 
  40.     LimitType limitType() default LimitType.CUSTOMER; 

6、切面代碼實現(xiàn)

  1. /** 
  2.  * @author fu 
  3.  * @description 限流切面實現(xiàn) 
  4.  * @date 2020/4/8 13:04 
  5.  */ 
  6. @Aspect 
  7. @Configuration 
  8. public class LimitInterceptor { 
  9.  
  10.     private static final Logger logger = LoggerFactory.getLogger(LimitInterceptor.class); 
  11.  
  12.     private static final String UNKNOWN = "unknown"
  13.  
  14.     private final RedisTemplate<String, Serializable> limitRedisTemplate; 
  15.  
  16.     @Autowired 
  17.     public LimitInterceptor(RedisTemplate<String, Serializable> limitRedisTemplate) { 
  18.         this.limitRedisTemplate = limitRedisTemplate; 
  19.     } 
  20.  
  21.     /** 
  22.      * @param pjp 
  23.      * @author fu 
  24.      * @description 切面 
  25.      * @date 2020/4/8 13:04 
  26.      */ 
  27.     @Around("execution(public * *(..)) && @annotation(com.xiaofu.limit.api.Limit)"
  28.     public Object interceptor(ProceedingJoinPoint pjp) { 
  29.         MethodSignature signature = (MethodSignature) pjp.getSignature(); 
  30.         Method method = signature.getMethod(); 
  31.         Limit limitAnnotation = method.getAnnotation(Limit.class); 
  32.         LimitType limitType = limitAnnotation.limitType(); 
  33.         String name = limitAnnotation.name(); 
  34.         String key; 
  35.         int limitPeriod = limitAnnotation.period(); 
  36.         int limitCount = limitAnnotation.count(); 
  37.  
  38.         /** 
  39.          * 根據(jù)限流類型獲取不同的key ,如果不傳我們會以方法名作為key 
  40.          */ 
  41.         switch (limitType) { 
  42.             case IP: 
  43.                 key = getIpAddress(); 
  44.                 break
  45.             case CUSTOMER: 
  46.                 key = limitAnnotation.key(); 
  47.                 break
  48.             default
  49.                 key = StringUtils.upperCase(method.getName()); 
  50.         } 
  51.  
  52.         ImmutableList<String> keys = ImmutableList.of(StringUtils.join(limitAnnotation.prefix(), key)); 
  53.         try { 
  54.             String luaScript = buildLuaScript(); 
  55.             RedisScript<Number> redisScript = new DefaultRedisScript<>(luaScript, Number.class); 
  56.             Number count = limitRedisTemplate.execute(redisScript, keys, limitCount, limitPeriod); 
  57.             logger.info("Access try count is {} for name={} and key = {}", count, name, key); 
  58.             if (count != null && count.intValue() <= limitCount) { 
  59.                 return pjp.proceed(); 
  60.             } else { 
  61.                 throw new RuntimeException("You have been dragged into the blacklist"); 
  62.             } 
  63.         } catch (Throwable e) { 
  64.             if (e instanceof RuntimeException) { 
  65.                 throw new RuntimeException(e.getLocalizedMessage()); 
  66.             } 
  67.             throw new RuntimeException("server exception"); 
  68.         } 
  69.     } 
  70.  
  71.     /** 
  72.      * @author fu 
  73.      * @description 編寫 redis Lua 限流腳本 
  74.      * @date 2020/4/8 13:24 
  75.      */ 
  76.     public String buildLuaScript() { 
  77.         StringBuilder lua = new StringBuilder(); 
  78.         lua.append("local c"); 
  79.         lua.append("\nc = redis.call('get',KEYS[1])"); 
  80.         // 調(diào)用不超過最大值,則直接返回 
  81.         lua.append("\nif c and tonumber(c) > tonumber(ARGV[1]) then"); 
  82.         lua.append("\nreturn c;"); 
  83.         lua.append("\nend"); 
  84.         // 執(zhí)行計算器自加 
  85.         lua.append("\nc = redis.call('incr',KEYS[1])"); 
  86.         lua.append("\nif tonumber(c) == 1 then"); 
  87.         // 從第一次調(diào)用開始限流,設(shè)置對應鍵值的過期 
  88.         lua.append("\nredis.call('expire',KEYS[1],ARGV[2])"); 
  89.         lua.append("\nend"); 
  90.         lua.append("\nreturn c;"); 
  91.         return lua.toString(); 
  92.     } 
  93.  
  94.  
  95.     /** 
  96.      * @author fu 
  97.      * @description 獲取id地址 
  98.      * @date 2020/4/8 13:24 
  99.      */ 
  100.     public String getIpAddress() { 
  101.         HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); 
  102.         String ip = request.getHeader("x-forwarded-for"); 
  103.         if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { 
  104.             ip = request.getHeader("Proxy-Client-IP"); 
  105.         } 
  106.         if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { 
  107.             ip = request.getHeader("WL-Proxy-Client-IP"); 
  108.         } 
  109.         if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { 
  110.             ip = request.getRemoteAddr(); 
  111.         } 
  112.         return ip; 
  113.     } 

7、控制層實現(xiàn)

我們將@Limit注解作用在需要進行限流的接口方法上,下邊我們給方法設(shè)置@Limit注解,在10秒內(nèi)只允許放行3個請求,這里為直觀一點用AtomicInteger計數(shù)。

  1. /** 
  2.  * @Author: fu 
  3.  * @Description: 
  4.  */ 
  5. @RestController 
  6. public class LimiterController { 
  7.  
  8.     private static final AtomicInteger ATOMIC_INTEGER_1 = new AtomicInteger(); 
  9.     private static final AtomicInteger ATOMIC_INTEGER_2 = new AtomicInteger(); 
  10.     private static final AtomicInteger ATOMIC_INTEGER_3 = new AtomicInteger(); 
  11.  
  12.     /** 
  13.      * @author fu 
  14.      * @description 
  15.      * @date 2020/4/8 13:42 
  16.      */ 
  17.     @Limit(key = "limitTest", period = 10, count = 3
  18.     @GetMapping("/limitTest1"
  19.     public int testLimiter1() { 
  20.  
  21.         return ATOMIC_INTEGER_1.incrementAndGet(); 
  22.     } 
  23.  
  24.     /** 
  25.      * @author fu 
  26.      * @description 
  27.      * @date 2020/4/8 13:42 
  28.      */ 
  29.     @Limit(key = "customer_limit_test", period = 10, count = 3, limitType = LimitType.CUSTOMER) 
  30.     @GetMapping("/limitTest2"
  31.     public int testLimiter2() { 
  32.  
  33.         return ATOMIC_INTEGER_2.incrementAndGet(); 
  34.     } 
  35.  
  36.     /** 
  37.      * @author fu 
  38.      * @description  
  39.      * @date 2020/4/8 13:42 
  40.      */ 
  41.     @Limit(key = "ip_limit_test", period = 10, count = 3, limitType = LimitType.IP) 
  42.     @GetMapping("/limitTest3"
  43.     public int testLimiter3() { 
  44.  
  45.         return ATOMIC_INTEGER_3.incrementAndGet(); 
  46.     } 
  47.  

8、測試

測試 「預期」 :連續(xù)請求3次均可以成功,第4次請求被拒絕。接下來看一下是不是我們預期的效果,請求地址: http://127.0.0.1:8080/limitTest1 ,用 postman 進行測試,有沒有 postman url直接貼瀏覽器也是一樣。

可以看到第四次請求時,應用直接拒絕了請求,說明我們的 Springboot + aop + lua 限流方案搭建成功。

以上 springboot + aop + Lua 限流實現(xiàn)是比較簡單的,旨在讓大家認識下什么是限流?如何做一個簡單的限流功能,面試要知道這是個什么東西。上面雖然說了幾種實現(xiàn)限流的方案,但選哪種還要結(jié)合具體的業(yè)務場景,不能為了用而用。

 

責任編輯:張燕妮 來源: 程序員內(nèi)點事
相關(guān)推薦

2020-06-10 10:12:32

2G退網(wǎng)5G運營商

2018-04-11 14:30:33

2018-05-14 22:58:14

戴爾

2023-02-03 09:52:10

開發(fā)者框架GoFrame

2019-06-19 15:40:06

分布式鎖RedisJava

2021-04-19 11:22:24

人工智能人臉識別科學

2020-06-08 17:35:27

Redis集群互聯(lián)網(wǎng)

2024-04-08 11:04:03

2022-12-21 08:40:05

限流器分布式限流

2021-09-17 12:18:53

NginxJavaScript前端

2017-02-20 10:17:53

華為

2018-07-16 08:29:54

redis集群限流

2024-06-05 10:31:50

2022-01-12 12:46:32

Go限流保障

2021-10-21 06:39:41

限流熔斷系統(tǒng)

2013-05-13 10:30:26

分布式架構(gòu)架構(gòu)設(shè)計網(wǎng)站架構(gòu)

2017-02-23 08:00:04

智能語音Click

2018-06-11 11:12:09

秒殺限流分布式

2018-06-19 09:35:51

分布式系統(tǒng)限流

2023-07-11 10:24:00

分布式限流算法
點贊
收藏

51CTO技術(shù)棧公眾號