resilience4j-ratelimiter 限流

简介

ratelimiter限制了服务被调用的次数,每隔一段时间重置该次数,服务在超出等待时间之后返回异常或者fallback方法

配置介绍

配置属性 默认值 描述
limitRefreshPeriod 500ns 时间段,每隔该时间段,服务被调用的总次数重置
limitForPeriod 50 每个时间段内服务可以被调用的最大总次数
timeoutDuration 5s 等待调用服务的时间,超出时间返回异常

演示使用

  1. 创建一个模拟的外部服务,服务执行完成需要2s的时间
  2. 自定义RateLimiterConfig,每5s服务只能调用5次,调用等待时间为10s
  3. 每隔50ms开启一个新线程调用外部服务

需要准备的依赖包,resilience4j的spring boot包,里面包括了resilience4j所有功能的包和自动配置功能

<dependency>
    <groupId>io.github.resilience4j</groupId>
    <artifactId>resilience4j-spring-boot2</artifactId>
    <version>1.7.0</version>
</dependency>

模拟服务

服务执行2s,打印时间和当前线程名称后返回

@Service
public class ExternalLowRateService {
    public void callService() {
        try {
            Thread.sleep(2000);
            System.out.println(LocalTime.now() + " Call processing finished = " + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

ratelimiter配置和使用

@SpringBootTest
class ExternalLowRateServiceTest {

    @Autowired
    ExternalLowRateService service;

    @Test
    void callService() throws InterruptedException {
        /*
          自定义RateLimiterConfig, 限制服务调用次数为5,每隔5s重置,最大等待时间为10s
         */
        RateLimiterConfig config = RateLimiterConfig.custom()
            .limitRefreshPeriod(Duration.ofSeconds(5))
            .limitForPeriod(5)
            .timeoutDuration(Duration.ofSeconds(10))
            .build();
        RateLimiter rateLimiter = RateLimiter.of("externalLowRateService", config);
        for (int i = 1; i <= 20; i++) {
            System.out.println(LocalTime.now() + " Starting service call = " + i);
            // 使用rateLimiter调用外部服务
            new Thread(() -> rateLimiter.executeRunnable(service::callService),"service-call-" + i).start();
            Thread.sleep(50);
        }
        Thread.sleep(12000);
    }
}

输出结果

  • 1-20次调用依次开始
  • 1-5次开始执行并返回
  • 5s后6-10次开始执行并返回
  • 16-20次调用已等待超过10s,返回异常
  • 11-15次调用执行并返回
04:41:12.846114900 Starting service call = 1
04:41:12.914934300 Starting service call = 2
04:41:12.977763900 Starting service call = 3
04:41:13.041593400 Starting service call = 4
04:41:13.104454900 Starting service call = 5
04:41:13.166494600 Starting service call = 6
04:41:13.230321600 Starting service call = 7
04:41:13.293139600 Starting service call = 8
04:41:13.355637600 Starting service call = 9
04:41:13.417592800 Starting service call = 10
04:41:13.480228600 Starting service call = 11
04:41:13.542253700 Starting service call = 12
04:41:13.604270 Starting service call = 13
04:41:13.665588600 Starting service call = 14
04:41:13.728248400 Starting service call = 15
04:41:13.789320300 Starting service call = 16
04:41:13.850204 Starting service call = 17
04:41:13.912728400 Starting service call = 18
04:41:13.975277900 Starting service call = 19
04:41:14.038369600 Starting service call = 20
04:41:14.859399800 Call processing finished = service-call-1
04:41:14.921328200 Call processing finished = service-call-2
04:41:14.983447400 Call processing finished = service-call-3
04:41:15.045475300 Call processing finished = service-call-4
04:41:15.107320600 Call processing finished = service-call-5
04:41:19.864071500 Call processing finished = service-call-9
04:41:19.864071500 Call processing finished = service-call-6
04:41:19.864071500 Call processing finished = service-call-8
04:41:19.864071500 Call processing finished = service-call-10
04:41:19.864071500 Call processing finished = service-call-7
Exception in thread "service-call-16" io.github.resilience4j.ratelimiter.RequestNotPermitted: RateLimiter 'externalLowRateService' does not permit further calls
    at io.github.resilience4j.ratelimiter.RequestNotPermitted.createRequestNotPermitted(RequestNotPermitted.java:43)
    at io.github.resilience4j.ratelimiter.RateLimiter.waitForPermission(RateLimiter.java:591)
    at io.github.resilience4j.ratelimiter.RateLimiter.lambda$decorateCheckedRunnable$3(RateLimiter.java:246)
    at io.vavr.CheckedRunnable.lambda$unchecked$0(CheckedRunnable.java:68)
    at io.github.resilience4j.ratelimiter.RateLimiter.executeRunnable(RateLimiter.java:872)
    at io.github.resilience4j.ratelimiter.RateLimiter.executeRunnable(RateLimiter.java:862)
    at io.ysh.eurekacientconsumer.service.ExternalLowRateServiceTest.lambda$callService$0(ExternalLowRateServiceTest.java:29)
    at java.base/java.lang.Thread.run(Thread.java:834)
Exception in thread "service-call-17" io.github.resilience4j.ratelimiter.RequestNotPermitted: RateLimiter 'externalLowRateService' does not permit further calls
    at io.github.resilience4j.ratelimiter.RequestNotPermitted.createRequestNotPermitted(RequestNotPermitted.java:43)
    at io.github.resilience4j.ratelimiter.RateLimiter.waitForPermission(RateLimiter.java:591)
    at io.github.resilience4j.ratelimiter.RateLimiter.lambda$decorateCheckedRunnable$3(RateLimiter.java:246)
    at io.vavr.CheckedRunnable.lambda$unchecked$0(CheckedRunnable.java:68)
    at io.github.resilience4j.ratelimiter.RateLimiter.executeRunnable(RateLimiter.java:872)
    at io.github.resilience4j.ratelimiter.RateLimiter.executeRunnable(RateLimiter.java:862)
    at io.ysh.eurekacientconsumer.service.ExternalLowRateServiceTest.lambda$callService$0(ExternalLowRateServiceTest.java:29)
    at java.base/java.lang.Thread.run(Thread.java:834)
Exception in thread "service-call-18" io.github.resilience4j.ratelimiter.RequestNotPermitted: RateLimiter 'externalLowRateService' does not permit further calls
    at io.github.resilience4j.ratelimiter.RequestNotPermitted.createRequestNotPermitted(RequestNotPermitted.java:43)
    at io.github.resilience4j.ratelimiter.RateLimiter.waitForPermission(RateLimiter.java:591)
    at io.github.resilience4j.ratelimiter.RateLimiter.lambda$decorateCheckedRunnable$3(RateLimiter.java:246)
    at io.vavr.CheckedRunnable.lambda$unchecked$0(CheckedRunnable.java:68)
    at io.github.resilience4j.ratelimiter.RateLimiter.executeRunnable(RateLimiter.java:872)
    at io.github.resilience4j.ratelimiter.RateLimiter.executeRunnable(RateLimiter.java:862)
    at io.ysh.eurekacientconsumer.service.ExternalLowRateServiceTest.lambda$callService$0(ExternalLowRateServiceTest.java:29)
    at java.base/java.lang.Thread.run(Thread.java:834)
Exception in thread "service-call-19" io.github.resilience4j.ratelimiter.RequestNotPermitted: RateLimiter 'externalLowRateService' does not permit further calls
    at io.github.resilience4j.ratelimiter.RequestNotPermitted.createRequestNotPermitted(RequestNotPermitted.java:43)
    at io.github.resilience4j.ratelimiter.RateLimiter.waitForPermission(RateLimiter.java:591)
    at io.github.resilience4j.ratelimiter.RateLimiter.lambda$decorateCheckedRunnable$3(RateLimiter.java:246)
    at io.vavr.CheckedRunnable.lambda$unchecked$0(CheckedRunnable.java:68)
    at io.github.resilience4j.ratelimiter.RateLimiter.executeRunnable(RateLimiter.java:872)
    at io.github.resilience4j.ratelimiter.RateLimiter.executeRunnable(RateLimiter.java:862)
    at io.ysh.eurekacientconsumer.service.ExternalLowRateServiceTest.lambda$callService$0(ExternalLowRateServiceTest.java:29)
    at java.base/java.lang.Thread.run(Thread.java:834)
Exception in thread "service-call-20" io.github.resilience4j.ratelimiter.RequestNotPermitted: RateLimiter 'externalLowRateService' does not permit further calls
    at io.github.resilience4j.ratelimiter.RequestNotPermitted.createRequestNotPermitted(RequestNotPermitted.java:43)
    at io.github.resilience4j.ratelimiter.RateLimiter.waitForPermission(RateLimiter.java:591)
    at io.github.resilience4j.ratelimiter.RateLimiter.lambda$decorateCheckedRunnable$3(RateLimiter.java:246)
    at io.vavr.CheckedRunnable.lambda$unchecked$0(CheckedRunnable.java:68)
    at io.github.resilience4j.ratelimiter.RateLimiter.executeRunnable(RateLimiter.java:872)
    at io.github.resilience4j.ratelimiter.RateLimiter.executeRunnable(RateLimiter.java:862)
    at io.ysh.eurekacientconsumer.service.ExternalLowRateServiceTest.lambda$callService$0(ExternalLowRateServiceTest.java:29)
    at java.base/java.lang.Thread.run(Thread.java:834)
04:41:24.863851800 Call processing finished = service-call-12
04:41:24.863851800 Call processing finished = service-call-15
04:41:24.863851800 Call processing finished = service-call-11
04:41:24.863851800 Call processing finished = service-call-14
04:41:24.863851800 Call processing finished = service-call-13

springboot自动配置

配置在application.yml中

  • configs:ratelimiter配置,可以配置多个
  • instances:ratelimiter实例名称,可以配置baseConfig指定具体的ratelimiter配置,也可以自行配置
resilience4j.ratelimiter:
  configs:
    default:
      limitForPeriod: 10
      limitRefreshPeriod: 1s
  instances:
    externalLowRateService:
      limitForPeriod: 5
      limitRefreshPeriod: 5s
      timeoutDuration: 10s

注解

注解@Bulkhead有两个属性:

  • name:ratelimiter的名称,对应yml文件中instances中的配置
  • fallbackMethod:方法名,超出等待时间的服务调用会执行该方法并返回
@Service
public class ExternalLowRateService {
   @RateLimiter(name = "externalLowRateService")
    public void callService() {
        try {
            Thread.sleep(2000);
            System.out.println(LocalTime.now() + " Call processing finished = " + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

测试方法

测试方法,没有显式的bulkhead配置和创建,直接执行服务调用即可,结果返回跟上面的测试一样

@SpringBootTest
class ExternalLowRateServiceTest {

    @Autowired
    ExternalLowRateService service;

    @Test
    void callService() throws InterruptedException {
        for (int i = 1; i <= 20; i++) {
            System.out.println(LocalTime.now() + " Starting service call = " + i);
            new Thread(service::callService,"service-call-" + i).start();
            Thread.sleep(50);
        }
        Thread.sleep(12000);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 225,151评论 6 523
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 96,465评论 3 405
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 172,429评论 0 368
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 61,147评论 1 301
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 70,149评论 6 400
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 53,614评论 1 315
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 41,965评论 3 429
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 40,950评论 0 279
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 47,486评论 1 324
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 39,524评论 3 347
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 41,640评论 1 355
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 37,228评论 5 351
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 42,976评论 3 340
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 33,407评论 0 25
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 34,552评论 1 277
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 50,215评论 3 381
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 46,714评论 2 366

推荐阅读更多精彩内容