Bootstrap

resilience4j-ratelimiter:限流器

resilience4j-ratelimiter:限流器,用作流控

依赖

<properties>
	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	<resilience4j.version>0.16.0</resilience4j.version>
</properties>
<dependency>
	<groupId>io.github.resilience4j</groupId>
	<artifactId>resilience4j-ratelimiter</artifactId>
	<version>${resilience4j.version}</version>
</dependency>

application.yml配置内容如下

resilience4j:
	ratelimiter:
		limiters:
			limiterA: # #RateLimiter名称
				limit-for-period: 1 # 每时间单位可执行处理数
				limit-refresh-period-in-millis: 10000 # 单位时间(毫秒)
				timeout-in-millis: 10000 # 获取令牌的等待超时时间, 超时为获取到令牌将抛出异常
			limiterB:
				limit-for-period: 1 # 每时间单位可执行处理数
				limit-refresh-period-in-millis: 10000 #单位时间(毫秒)
				timeout-in-millis: 10000 # 获取令牌的等待超时时间, 超时为获取到令牌将抛出异常

api方式使用

// 创建限流器配置
RateLimiterConfig config =  RateLimiterConfig.custom()
				.limitRefreshPeriod(Duration.ofMillis(1000))
				.limitForPeriod(1)
				.timeoutDuration(Duration.ofMillis(1000))
				.build();
// 创建限流器注册器RateLimiterRegistry
RateLimiterRegistry rateLimiterRegistry = RateLimiterRegistry.of(config);
// 通过RateLimiterRegistry来创建限流器
RateLimiter rateLimiterWithDefaultConfig = rateLimiterRegistry.rateLimiter("backend1");
RateLimiter rateLimiterWithCustomConfig = rateLimiterRegistry.rateLimiter("backend2", config);
// 通过RateLimiter创建限流器
RateLimiter rateLimiter = RateLimiter.of("emailSendRateLimiter", config);
// 限流器指标:等待线程数,可用令牌数
RateLimiter.Metrics metrics = rateLimiter.getMetrics();
rateLimiter.getEventPublisher().onSuccess(event -> {
   
	System.out.println(event.getEventType() + ":::可用令牌数: " + metrics.getAvailablePermissions() + ", 等待线程数: "
			+ metrics.getNumberOfWaitingThreads());
}).onFailure(event -> {
   
	System.out.println(event.getEventType() + ":::可用令牌数: " + metrics.getAvailablePermissions() + ", 等待线程数: "
			+ metrics.getNumberOfWaitingThreads());
});
// 创建一个受RateLimiter限制的runnable。
Runnable task = RateLimiter.decorateRunnable(rateLimiter, new Runnable() {
   
			@Override
			public void run() {
   
				// TODO Auto-generated method stub
				
			}
		});
// 装饰并执行装饰的Runnable。
rateLimiter.executeRunnable(new Runnable() {
   
			@Override
			public void run() {
   
			}
		});
;