最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解Springboot分布式限流實踐

 更新時間:2019年06月06日 10:43:11   作者:CarryChan  
這篇文章主要介紹了詳解Springboot分布式限流實踐 ,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

高并發(fā)訪問時,緩存、限流、降級往往是系統(tǒng)的利劍,在互聯(lián)網(wǎng)蓬勃發(fā)展的時期,經(jīng)常會面臨因用戶暴漲導致的請求不可用的情況,甚至引發(fā)連鎖反映導致整個系統(tǒng)崩潰。這個時候常見的解決方案之一就是限流了,當請求達到一定的并發(fā)數(shù)或速率,就進行等待、排隊、降級、拒絕服務(wù)等...

限流算法介紹

a、令牌桶算法

令牌桶算法的原理是系統(tǒng)會以一個恒定的速度往桶里放入令牌,而如果請求需要被處理,則需要先從桶里獲取一個令牌,當桶里沒有令牌可取時,則拒絕服務(wù)。 當桶滿時,新添加的令牌被丟棄或拒絕。

b、漏桶算法

其主要目的是控制數(shù)據(jù)注入到網(wǎng)絡(luò)的速率,平滑網(wǎng)絡(luò)上的突發(fā)流量,數(shù)據(jù)可以以任意速度流入到漏桶中。漏桶算法提供了一種機制,通過它,突發(fā)流量可以被整形以便為網(wǎng)絡(luò)提供一個穩(wěn)定的流量。 漏桶可以看作是一個帶有常量服務(wù)時間的單服務(wù)器隊列,如果漏桶為空,則不需要流出水滴,如果漏桶(包緩存)溢出,那么水滴會被溢出丟棄

c、計算器限流

計數(shù)器限流算法是比較常用一種的限流方案也是最為粗暴直接的,主要用來限制總并發(fā)數(shù),比如數(shù)據(jù)庫連接池大小、線程池大小、接口訪問并發(fā)數(shù)等都是使用計數(shù)器算法

如:使用AomicInteger來進行統(tǒng)計當前正在并發(fā)執(zhí)行的次數(shù),如果超過域值就直接拒絕請求,提示系統(tǒng)繁忙

限流具體代碼實踐

a、導入依賴

<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)的配置項

spring.redis.host=192.168.68.110
spring.redis.port=6379
spring.redis.password=123456

默認情況下spring-boot-data-redis為我們提供了StringRedisTemplate但是滿足不了其它類型的轉(zhuǎn)換,所以還是得自己去定義其它類型的模板

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 "";

  /**
   * 給定的時間段
   * 單位秒
   *
   * @return int
   */
  int period();

  /**
   * 最多的訪問限制次數(shù)
   *
   * @return int
   */
  int count();

  /**
   * 類型
   *
   * @return LimitType
   */
  LimitType limitType() default LimitType.CUSTOMER;
}
package com.carry.enums;

public enum LimitType {
  /**
   * 自定義key
   */
  CUSTOMER,
  /**
   * 根據(jù)請求者IP
   */
  IP;
}

e、Limit 攔截器(AOP)

我們可以通過編寫 Lua 腳本實現(xiàn)自己的API,核心就是調(diào)用execute方法傳入我們的 Lua 腳本內(nèi)容,然后通過返回值判斷是否超出我們預(yù)期的范圍,超出則給出錯誤提示。

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)用不超過最大值,則直接返回
    lua.append("\nif c and tonumber(c) > tonumber(ARGV[1]) then");
    lua.append("\nreturn c;");
    lua.append("\nend");
    // 執(zhí)行計算器自加
    lua.append("\nc = redis.call('incr',KEYS[1])");
    lua.append("\nif tonumber(c) == 1 then");
    // 從第一次調(diào)用開始限流,設(shè)置對應(yīng)鍵值的過期
    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()注解,如下代碼會在 Redis 中生成過期時間為 100s 的 key = test 的記錄,特意定義了一個AtomicInteger用作測試

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)最多可以訪問10次
    return ATOMIC_INTEGER.incrementAndGet();
  }
}

注意:上面例子保存在redis中的key值應(yīng)該為“l(fā)imittest”,即@Limit中prefix的值+key的值

測試

我們在postman中快速訪問localhost:8080/test,當訪問數(shù)超過10時出現(xiàn)以下結(jié)果

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java代碼實現(xiàn)哈希表(google 公司的上機題)

    Java代碼實現(xiàn)哈希表(google 公司的上機題)

    這篇文章主要介紹了Java 哈希表詳解(google 公司的上機題),本文通過圖文實例相結(jié)合給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-03-03
  • jdk源碼閱讀Collection詳解

    jdk源碼閱讀Collection詳解

    這篇文章主要介紹了jdk源碼閱讀Collection詳解,具有一定借鑒價值,需要的朋友可以參考下
    2017-12-12
  • 淺談Spring中幾個PostProcessor的區(qū)別與聯(lián)系

    淺談Spring中幾個PostProcessor的區(qū)別與聯(lián)系

    這篇文章主要介紹了淺談Spring中幾個PostProcessor的區(qū)別與聯(lián)系,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • SpringBoot下如何實現(xiàn)支付寶接口的使用

    SpringBoot下如何實現(xiàn)支付寶接口的使用

    這篇文章主要介紹了SpringBoot下如何實現(xiàn)支付寶接口的使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-11-11
  • 深入理解java重載和重寫

    深入理解java重載和重寫

    這篇文章主要介紹了Java方法重載和重寫原理區(qū)別解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2021-07-07
  • Spring中Bean命名的方式總結(jié)

    Spring中Bean命名的方式總結(jié)

    在?Spring?框架中,每個?bean?必須至少有一個唯一的名稱,這篇文章主要為大家詳細介紹了Spring中Bean命名的各種方式,感興趣的小伙伴可以跟隨小編一起學習一下
    2023-12-12
  • SpringBoot瘦身打包部署的實現(xiàn)

    SpringBoot瘦身打包部署的實現(xiàn)

    這篇文章主要介紹了SpringBoot瘦身打包部署的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-04-04
  • java sqlserver text 類型字段讀取方法

    java sqlserver text 類型字段讀取方法

    有這樣一個需求,需要將原本存儲在數(shù)據(jù)庫中的文檔轉(zhuǎn)存至文件系統(tǒng)中,于是寫了一個簡單的程序完成此功能
    2012-11-11
  • SpringBoot 使用hibernate validator校驗

    SpringBoot 使用hibernate validator校驗

    這篇文章主要介紹了SpringBoot 使用hibernate validator校驗,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-11-11
  • Jenkins集成sonarQube實現(xiàn)代碼質(zhì)量檢查過程圖解

    Jenkins集成sonarQube實現(xiàn)代碼質(zhì)量檢查過程圖解

    這篇文章主要介紹了Jenkins集成sonarQube實現(xiàn)代碼質(zhì)量檢查過程圖解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-09-09

最新評論

招远市| 新丰县| 扶绥县| 莱西市| 木兰县| 旺苍县| 西乌珠穆沁旗| 临清市| 三门县| 靖西县| 庆元县| 兴安县| 松潘县| 鄂托克前旗| 大石桥市| 江门市| 新密市| 巴中市| 平安县| 辽宁省| 荔波县| 灌阳县| 阜阳市| 马边| 宜君县| 阿坝县| 图们市| 克什克腾旗| 和顺县| 尼玛县| 甘南县| 云梦县| 施秉县| 肥乡县| 永丰县| 米林县| 辛集市| 蚌埠市| 利川市| 佛山市| 祁阳县|