0


限流器 github的ratelimiter

一、pom依赖

<!--限流器--><dependency><groupId>io.github.resilience4j</groupId><artifactId>resilience4j-ratelimiter</artifactId><version>1.7.0</version></dependency>

二、限流器配置

packagecom.test.config;importio.github.resilience4j.ratelimiter.RateLimiter;importio.github.resilience4j.ratelimiter.RateLimiterConfig;importio.github.resilience4j.ratelimiter.RateLimiterRegistry;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importjava.time.Duration;@ConfigurationpublicclassRateConfig{@Value("${ratelimit.qps.handshake:100}")privateint handshakeQps;// 默认QPS 100@Value("${ratelimit.qps.msg:5000}")privateint msgQps;// 默认QPS 5000//3s内只能发送一次请求@Bean(name ="test")publicRateLimitertest(){RateLimiterConfig rateLimiterConfig =RateLimiterConfig.custom().timeoutDuration(Duration.ofMillis(0))// 不等待 直接失败.limitRefreshPeriod(Duration.ofMillis(3000))// 表示每隔多长时间刷新一次限流计数器   这里3s.limitForPeriod(1)// 一个限流周期内允许的最大请求数       这里1次.build();returnRateLimiterRegistry.of(rateLimiterConfig).rateLimiter("handshake");}//握手的限流策略(0.1s内允许10个握手连接)@Bean(name ="handshake")publicRateLimiterhandshakeRateLimiter(){int tenMillis =10;// 时间单位同时除 10RateLimiterConfig config =RateLimiterConfig.custom().timeoutDuration(Duration.ofMillis(0))// 不等待 直接失败.limitRefreshPeriod(Duration.ofMillis(1000/ tenMillis))// 按 100ms 刷新 更平滑.limitForPeriod(handshakeQps / tenMillis)// 平均 QPS.build();returnRateLimiterRegistry.of(config).rateLimiter("handshake");}//发送消息的限流策略(0.1s内允许发送500个消息)@Bean(name ="sendMsg")publicRateLimitersendMsgRateLimiter(){int tenMillis =10;// 时间单位同时除 10RateLimiterConfig config =RateLimiterConfig.custom().timeoutDuration(Duration.ofMillis(0))// 不等待 直接失败.limitRefreshPeriod(Duration.ofMillis(1000/ tenMillis))// 按 100ms 刷新 更平滑.limitForPeriod(msgQps / tenMillis)// 平均 QPS.build();returnRateLimiterRegistry.of(config).rateLimiter("sendMsg");}}

三、限流器使用

@RestControllerpublicclassTestController{@Resource(name ="test")RateLimiter test;@Resource(name ="handshake")RateLimiter handshake;@Resource(name ="sendMsg")RateLimiter sendMsg;@GetMapping("/test")publicStringtest(){boolean b1 = test.acquirePermission();boolean b2 = handshake.acquirePermission();boolean b3 = sendMsg.acquirePermission();System.out.println("sendMsg: "+ b1 +"   handshake: "+ b2 +"   sendMsg: "+ b3);return"test";}}
标签: github

本文转载自: https://blog.csdn.net/weixin_44635157/article/details/136210529
版权归原作者 飘然生 所有, 如有侵权,请联系我们删除。

“限流器 github的ratelimiter”的评论:

还没有评论