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

詳解Springboot分布式限流實(shí)踐

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

高并發(fā)訪問時(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í)候常見的解決方案之一就是限流了,當(dāng)請(qǐng)求達(dá)到一定的并發(fā)數(shù)或速率,就進(jìn)行等待、排隊(duì)、降級(jí)、拒絕服務(wù)等...

限流算法介紹

a、令牌桶算法

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

b、漏桶算法

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

c、計(jì)算器限流

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

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

限流具體代碼實(shí)踐

a、導(dǎo)入依賴

<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但是滿足不了其它類型的轉(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 "";

  /**
   * 給定的時(shí)間段
   * 單位秒
   *
   * @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ù)請(qǐng)求者IP
   */
  IP;
}

e、Limit 攔截器(AOP)

我們可以通過編寫 Lua 腳本實(shí)現(xiàn)自己的API,核心就是調(diào)用execute方法傳入我們的 Lua 腳本內(nèi)容,然后通過返回值判斷是否超出我們預(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)用不超過最大值,則直接返回
    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)用開始限流,設(shè)置對(duì)應(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()注解,如下代碼會(huì)在 Redis 中生成過期時(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)最多可以訪問10次
    return ATOMIC_INTEGER.incrementAndGet();
  }
}

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

測(cè)試

我們?cè)趐ostman中快速訪問localhost:8080/test,當(dāng)訪問數(shù)超過10時(shí)出現(xiàn)以下結(jié)果

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

相關(guān)文章

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

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

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

    jdk源碼閱讀Collection詳解

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

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

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

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

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

    深入理解java重載和重寫

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

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

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

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

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

    java sqlserver text 類型字段讀取方法

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

    SpringBoot 使用hibernate validator校驗(yàn)

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

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

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

最新評(píng)論

外汇| 揭东县| 缙云县| 嵊泗县| 开鲁县| 突泉县| 崇左市| 比如县| 茂名市| 德兴市| 岚皋县| 鹿邑县| 新巴尔虎右旗| 昌都县| 海淀区| 平利县| 呼图壁县| 民勤县| 米泉市| 平湖市| 璧山县| 凤庆县| 河东区| 奉化市| 三门县| 阿尔山市| 绩溪县| 龙南县| 株洲县| 黑水县| 台东市| 桐梓县| 吐鲁番市| 江华| 安多县| 赣州市| 蒲江县| 长岭县| 临夏市| 蒙城县| 米泉市|