目录
AddRequestHeader GatewayFilter factory
AddRequestHeadersIfNotPresent GatewayFilter factory
AddRequestParameter GatewayFilter Factory
AddResponseHeader GatewayFilter Factory
CircuitBreaker GatewayFilter factory
circuit breaker based on the status code
PrefixPath GatewayFilter factory
StripPrefix GatewayFilter factory
RewritePath GatewayFilter factory
RequestRateLimiter GatewayFilter factory
default-filters
自定义GatewayFilter
多filter的运行
AddRequestHeader
GatewayFilter
factory
添加对应key和value
server:
port: 9000
spring:
cloud:
gateway:
routes:
- id: my_route
uri: http://localhost:7070
predicates:
- Path=/info/**
filters:
- AddRequestHeader=X-Request-Color, blue
controller获取请求头遍历输出
postman加请求头也能输出
AddRequestHeadersIfNotPresent
GatewayFilter
factory
可以添加多组key和value(请求头不存在对应key的情况下)
server:
port: 9000
spring:
cloud:
gateway:
routes:
- id: my_route
uri: http://localhost:7070
predicates:
- Path=/info/**
filters:
- AddRequestHeadersIfNotPresent=X-Request-Color:blue,school:rjxy
@GetMapping("/allHeaders")
public String allHeadersHandle(HttpServletRequest request){
StringBuilder sb = new StringBuilder();
//获取请求头所有的key
Enumeration<String> headerNames = request.getHeaderNames();
//遍历所有key
while (headerNames.hasMoreElements()) {
//获取key
String name = headerNames.nextElement();
sb.append(name+"===");
//获取当前key的所有value
Enumeration<String> headers = request.getHeaders(name);
//遍历所有value
while (headers.hasMoreElements()) {
//将当前遍历的value追加到sb中
sb.append(headers.nextElement()+"");
}
sb.append("<br>");
}
return sb.toString();
}
controller进行请求头遍历输出,添加成功
AddRequestParameter
GatewayFilter
Factory
添加请求参数
server:
port: 9000
spring:
cloud:
gateway:
routes:
- id: my_route
uri: http://localhost:7070
predicates:
- Path=/info/**
filters:
- AddRequestParameter=red, blue
controller
@GetMapping("/params")
public String paramsHandle(String red){
return red;
}
获取成功
AddResponseHeader
GatewayFilter
Factory
响应修改
server:
port: 9000
spring:
cloud:
gateway:
routes:
- id: my_route
uri: http://localhost:7070
predicates:
- Path=/info/**
filters:
- AddResponseHeader=X-Response-color, Blue
- AddResponseHeader=X-Response-color, Red
直接F12查看响应头,添加成功
CircuitBreaker GatewayFilter factory
熔断过滤工厂,完成网关层的服务熔断与降级
server:
port: 9000
spring:
cloud:
gateway:
routes:
- id: my_route
uri: http://localhost:7070
predicates:
- Path=/info/**
filters:
- name: CircuitBreaker
args:
name: myCircuitBreaker
fallbackUri: forward:/fb
访问http://localhost:7070不成功时,降级访问forward:/fb
降级controller
@GetMapping("/fb")
public String fallbackHandle(){
return "This is the Gateway Fallback";
}
测试,直接不启动7070,访问9000,熔断成功
circuit breaker based on the status code
PrefixPath
GatewayFilter
factory
server:
port: 9000
spring:
cloud:
gateway:
routes:
- id: my_route
uri: http://localhost:8081
predicates:
- Path=/student/**
filters:
- PrefixPath=/provider
匹配字段,加上前缀,子模块自动添加路径
测试成功
StripPrefix
GatewayFilter
factory
去除指定的请求路径
server:
port: 9000
spring:
cloud:
gateway:
routes:
- id: my_route
uri: http://localhost:8081
predicates:
- Path=/aa/bb/provider/student/**
filters:
- StripPrefix=2
去除/aa/bb
测试成功
RewritePath
GatewayFilter
factory
重写路径
server:
port: 9000
spring:
cloud:
gateway:
routes:
- id: my_route
uri: http://localhost:8081
predicates:
- Path=/red/blue/**
filters:
- RewritePath=/red/blue,/provider/student
// - RewritePath=/red/?(?<segment>.*), /$\{segment}
匹配路径,替换成指定路径
RequestRateLimiter
GatewayFilter
factory
通过令牌桶算法对进来的请求进行限流
导入依赖
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis-reactive -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
<version>3.0.5</version>
</dependency>
添加限流键解析器
在启动类中添加一个限流键解析器,其用于从请求中解析出需要限流的key。
本例指定的是根据请求的host或ip进行限流。
package com.guo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import reactor.core.publisher.Mono;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
KeyResolver userKeyResolver() {
return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
}
}
修改配置文件
server:
port: 9000
spring:
cloud:
gateway:
routes:
- id: my_route
uri: http://localhost:8081
predicates:
- Path=/**
filters:
# replenishRate 填充率
- name: RequestRateLimiter
args:
key-resolver: "#{@userKeyResolver}"
redis-rate-limiter.replenishRate: 2
redis-rate-limiter.burstCapacity: 5
redis-rate-limiter.requestedTokens: 1
data:
redis:
host: 127.0.0.1
port: 6379
成功
default-filters
server:
port: 9000
spring:
cloud:
gateway:
default-filters:
- AddRequestHeader=X-Request-Color, Default-Blue
routes:
- id: my_route
uri: http://localhost:7070
predicates:
- Path=/info/header
- id: my_route
uri: http://localhost:7070
predicates:
- Path=/info/headers
测试成功
自定义GatewayFilter
AddHeaderGatewayFilter.java
public class AddHeaderGatewayFilter implements GatewayFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest()
.mutate()
.header("X-Request-Color", "filter-Red")
.build();
ServerWebExchange webExchange = exchange.mutate().request(request).build();
return chain.filter(webExchange);
}
}
调用自定义的GatewayFilter
@Bean
public RouteLocator routeLocator(RouteLocatorBuilder builder){
return builder.routes()
.route("my_router2",
ps ->ps.path("/info/**")
.filters(fs->fs.filter(new AddHeaderGatewayFilter()))
.uri("http://localhost:7070"))
.build();
}
测试成功
多filter的运行
OneGateWayFilter.java
@Slf4j
public class OneGateWayFilter implements GatewayFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
long startTime = System.currentTimeMillis();
log.info("oneFilter-pre:"+startTime);
exchange.getAttributes().put("startTime",startTime);
return chain.filter(exchange).then(
Mono.fromRunnable(()->{
log.info("oneFilter------post");
Long startTimeAttr = (Long) exchange.getAttributes().get("startTime");
long elaspedTime = System.currentTimeMillis() - startTimeAttr;
log.info("所有过滤器执行的时间(毫秒)为:"+elaspedTime);
})
);
}
}
TwoGateWayFilter.java
@Slf4j
public class TwoGateWayFilter implements GatewayFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
log.info("TwoFilter----pre");
return chain.filter(exchange).then(
Mono.fromRunnable(()->{
log.info("TwoFilter------post");
})
);
}
}
ThreeGateWayFilter.java
@Slf4j
public class ThreeGateWayFilter implements GatewayFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
log.info("ThreeFilter----pre");
return chain.filter(exchange).then(
Mono.fromRunnable(()->{
log.info("ThreeFilter------post");
})
);
}
}
测试结果