GateWay三大核心概念:断言(Predicate),路由(Route),过滤(Filter)
路由,断言配置
server:
port: 9527
spring:
application:
name: cloud-gateway
cloud:
gateway:
discovery:
locator:
enabled: true # 开启从注册中心动态创建路由的功能,利用微服务名称进行路由
routes: #路由配置
- id: payment_route # 路由id,建议配合服务名
uri:lb://CLOUD-PAYMENT-SERVICE #根据微服务名称进行路由,并且实现负载均衡功能
predicates:
- Path=/payment/get/** # 断言,路径相匹配的进行路由
- id: payment_route2
uri: http://localhost:8001 #匹配路由名
predicates: #断言配置,所有断言为true才会进行路由。
- Path=/payment/lb/**
# - After=2020-03-01T12:08:15.582+08:00[Asia/Shanghai] #在此时间后该路由才生效
# - Cookie=username,mihacker
# - Header=X-Request-Id, \d+ #请求头要有X-Request-Id属性,并且值为正数 第二个参数为正则表达式
# - Method=GET
# - Query=param, \d+ #要有参数名param,并且值为正数才会跳转路由 第二个参数为正则表达式
# - Host=**.con
# - Between=2020-03-06T12:08:15.582+08:00[Asia/Shanghai],2020-03-06T12:08:15.582+08:00[Asia/Shanghai]
# - Before=2020-03-06T12:08:15.582+08:00[Asia/Shanghai]
eureka:
instance:
instance-id: gateway-service #微服务名称
prefer-ip-address: true #是否显示微服务IP地址
hostname: cloud-gateway-service #
client:
register-with-eureka: true #是否将自己注册进Eureka Server,默认为true
fetch-registry: true #是否从Eureka 抓取已有的注册信息,默认为true,单节点无所谓,集群必须设为true才能配合ribbon使用负载均衡
service-url:
defaultZone: http://eureka7001:7001/eureka,http://eureka7002:7002/eureka #Eureka集群配置
创建全局过滤器
/**
* gateway全局过滤器实现
*/
@Component
public class GateWayFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String user = exchange.getRequest().getQueryParams().getFirst("user");
if (user == null) {
exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
return exchange.getResponse().setComplete();
}
return chain.filter(exchange);
}
@Override
public int getOrder() {
return 0;
}
}