首先看pom的内容
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.8.RELEASE
com.eem
getway
0.0.1-SNAPSHOT
getway
Demo project for Spring Boot
1.8
Greenwich.SR3
org.springframework.cloud
spring-cloud-starter-gateway
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
org.springframework.boot
spring-boot-starter-actuator
org.springframework.boot
spring-boot-starter-webflux
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-data-redis
com.github.vladimir-bukhtoyarov
bucket4j-core
4.0.0
org.springframework.boot
spring-boot-starter-data-redis-reactive
redis.clients
jedis
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import
org.springframework.boot
spring-boot-maven-plugin
这里的springboot的版本是2.1.8
springcloud的版本是 Greenwich.SR3
第一种实现方式如下: 需要用redis,根据自己情况安装即可
启动类和以前的一样没有啥就不写了.
配置类如下:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RemoteKeyResolver {
@Bean(name="remoteAddrKeyResolver")
public RemoteAddrKeyResolver remoteAddrKeyResolver() {
return new RemoteAddrKeyResolver();
}
}
引用类如下
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
public class RemoteAddrKeyResolver implements KeyResolver{
public static final String BEAN_NAME = "remoteAddrKeyResolver";
@Override
public Mono resolve(ServerWebExchange exchange) {
System.out.println("hello");
Mono just = Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
return just;
}
}
配置文件如下:
server:
port: 9701
eureka:
client:
registerWithEureka: true
fetchRegistry: true
serviceUrl:
defaultZone: http://localhost:9601/eureka/
spring:
redis:
host: localhost
port: 6379
database: 0
lettuce:
pool:
#连接池最大连接数(使用负值表示没有限制)
max-active: 300
#连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1s
#连接池中的最大空闲连接
max-idle: 100
#连接池中的最小空闲连接
min-idle: 20
application:
name: getway
cloud:
gateway:
routes:
- id: getway
#uri: lb://hello # 这个也可以 lb://为固定写法,表示开启负载均衡;hello即服务在注册的名字
uri: http://localhost:9606
predicates:
- Path=/hello/**
filters:
- StripPrefix=1 # 这个必须要有,否则就是不能显示
- name: RequestRateLimiter
args:
# 令牌桶每秒填充平均速率,即行等价于允许用户每秒处理多少个请求平均数
redis-rate-limiter.replenishRate: 1
# 令牌桶的容量,允许在一秒钟内完成的最大请求数
redis-rate-limiter.burstCapacity: 6
# 用于限流的键的解析器的 Bean 对象的名字。它使用 SpEL 表达式根据#{@beanName}从 Spring 容器中获取 Bean 对象。
key-resolver: "#{@remoteAddrKeyResolver}"
然后在别的项目,比如服务注册,服务提供就不写了,然后在浏览器输入http://localhost:9701/hello/get1就可以显示正确内容.
第二种实现方式如下,这里使用配置类实现,配置类如下
import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket;
import io.github.bucket4j.Bucket4j;
import io.github.bucket4j.Refill;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class LimitFilter implements GatewayFilter, Ordered {
private final Logger logger = LoggerFactory.getLogger(LimitFilter.class);
int capacity;
int refillTokens;
Duration refillDuration;
public LimitFilter(int capacity, int refillTokens, Duration refillDuration) {
this.capacity = capacity;
this.refillTokens = refillTokens;
this.refillDuration = refillDuration;
}
private static final Map CACHE = new ConcurrentHashMap<>();
private Bucket createNewBucket() {
Refill refill = Refill.of(refillTokens,refillDuration);
Bandwidth limit = Bandwidth.classic(capacity,refill);
return Bucket4j.builder().addLimit(limit).build();
}
@Override
public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String ip = exchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
Bucket bucket = CACHE.computeIfAbsent(ip,k -> createNewBucket());
logger.info("IP: " + ip + ",TokenBucket Available Tokens: " + bucket.getAvailableTokens());
if (bucket.tryConsume(1)) {
return chain.filter(exchange);
} else {
exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
return exchange.getResponse().setComplete();
}
}
@Override
public int getOrder() {
return 0;
}
}
启动类:
import com.eem.getway.config.LimitFilter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import java.time.Duration;
@SpringBootApplication
@EnableEurekaClient
public class GetwayApplication {
public static void main(String[] args) {
SpringApplication.run(GetwayApplication.class, args);
}
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
//增加一个path匹配,以"/gateway/hello/"开头的请求都在此路由
.route(r -> r.path("/hello/**")
//表示将路径中的第一级参数删除,用剩下的路径与provider的路径做拼接,
//这里就是"lb://provider/hello/",能匹配到provider的HelloController的路径
.filters(f -> f.stripPrefix(1)
//.filter(new LimitFilter(10,1, Duration.ofSeconds(1))) //限流设置
//在请求的header中添加一个key&value
.addRequestHeader("extendtag", "geteway-" + System.currentTimeMillis()))
//指定匹配服务provider,lb是load balance的意思
.uri("lb://hello")
).build();
}
}
配置文件如下:
server:
port: 9701
eureka:
client:
registerWithEureka: true
fetchRegistry: true
serviceUrl:
defaultZone: http://localhost:9601/eureka/,http://localhost:9602/eureka/
spring:
redis:
host: localhost
port: 6379
database: 0
lettuce:
pool:
#连接池最大连接数(使用负值表示没有限制)
max-active: 300
#连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1s
#连接池中的最大空闲连接
max-idle: 100
#连接池中的最小空闲连接
min-idle: 20
application:
name: getway
也可以实现限流功能.
稍后,我讲会把所有代码上传.