分析:上述配置provider方提供均是写死的,需要改造。
默认情况下,Gateway会根据注册中心的服务列表,以注册中心上微服务名为路径创建动态路由进行转发,从而实现动态路由的功能。将uri配置为微服务名,并负载均衡
server: port: 9527 spring: application: name: cloud-gateway cloud: gateway: discovery: locator: enabled: true # 开启从注册中心动态创建路由的功能,利用微服务名称进行路由 routes: - id: payment_route # 路由的id,没有规定规则但要求唯一,建议配合服务名 #匹配后提供服务的路由地址 # uri: http://localhost:8001 uri: lb://CLOUD-PAYMENT-SERVICE predicates: - Path=/payment/get/** # 断言,路径相匹配的进行路由 #- After=2017-01-20T17:42:47.789-07:00[America/Denver] #- Before=2017-01-20T17:42:47.789-07:00[America/Denver] #- COOKIE=username,zzyy #- Header=X-Request-Id, \d+ #请求头要有X-Request-Id属性,并且值为正数 #- Host=**.atguigu.com #- Method=GET #- Query=username, \d+ # 要有参数名username并且值还要是正整数才能路由 # 过滤 #filters: # - AddRequestHeader=X-Request-red, blue - id: payment_route2 uri: lb://CLOUD-PAYMENT-SERVICE # uri: http://localhost:8001 predicates: Path=/payment/lb/** #断言,路径相匹配的进行路由 eureka: instance: hostname: cloud-gateway-service client: fetch-registry: true register-with-eureka: true service-url: defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
官网:https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/#gateway-request-predicates-factories,
可以对路由进行更精细的控制,例如header、COOKIE等等。
官网:https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/#gatewayfilter-factories
Filter分类:Gateway Fliter(单一31种)、Global Filter(全局--10种)
自定义过滤器类实现GlobalFilter,Orderd接口即可
@Component @Slf4j public class MyLogGatewayFilter implements GlobalFilter, Ordered { @Override public Monofilter(ServerWebExchange exchange, GatewayFilterChain chain) { log.info("come in global filter: {}", new Date()); ServerHttpRequest request = exchange.getRequest(); String uname = request.getQueryParams().getFirst("uname"); if (uname == null) { log.info("用户名为null,非法用户"); exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE); return exchange.getResponse().setComplete(); } // 放行 return chain.filter(exchange); } /** * 过滤器加载的顺序 越小,优先级别越高 * * @return */ @Override public int getOrder() { return 0; } }
Github地址:https://github.com/Simple-Coder/cloud2020