一、pom依赖
<!--限流器-->
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-ratelimiter</artifactId>
<version>1.7.0</version>
</dependency>
二、限流器配置
package com.test.config;
import io.github.resilience4j.ratelimiter.RateLimiter;
import io.github.resilience4j.ratelimiter.RateLimiterConfig;
import io.github.resilience4j.ratelimiter.RateLimiterRegistry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.Duration;
@Configuration
public class RateConfig {
@Value("${ratelimit.qps.handshake:100}")
private int handshakeQps;
@Value("${ratelimit.qps.msg:5000}")
private int msgQps;
@Bean(name = "test")
public RateLimiter test() {
RateLimiterConfig rateLimiterConfig = RateLimiterConfig.custom()
.timeoutDuration(Duration.ofMillis(0))
.limitRefreshPeriod(Duration.ofMillis(3000))
.limitForPeriod(1)
.build();
return RateLimiterRegistry.of(rateLimiterConfig).rateLimiter("handshake");
}
@Bean(name = "handshake")
public RateLimiter handshakeRateLimiter() {
int tenMillis = 10;
RateLimiterConfig config = RateLimiterConfig.custom()
.timeoutDuration(Duration.ofMillis(0))
.limitRefreshPeriod(Duration.ofMillis(1000 / tenMillis))
.limitForPeriod(handshakeQps / tenMillis)
.build();
return RateLimiterRegistry.of(config).rateLimiter("handshake");
}
@Bean(name = "sendMsg")
public RateLimiter sendMsgRateLimiter() {
int tenMillis = 10;
RateLimiterConfig config = RateLimiterConfig.custom()
.timeoutDuration(Duration.ofMillis(0))
.limitRefreshPeriod(Duration.ofMillis(1000 / tenMillis))
.limitForPeriod(msgQps / tenMillis)
.build();
return RateLimiterRegistry.of(config).rateLimiter("sendMsg");
}
}

- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
三、限流器使用
@RestController
public class TestController {
@Resource(name = "test")
RateLimiter test;
@Resource(name = "handshake")
RateLimiter handshake;
@Resource(name = "sendMsg")
RateLimiter sendMsg;
@GetMapping("/test")
public String test() {
boolean b1 = test.acquirePermission();
boolean b2 = handshake.acquirePermission();
boolean b3 = sendMsg.acquirePermission();
System.out.println("sendMsg: " + b1 + " handshake: " + b2 + " sendMsg: " + b3);
return "test";
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22