Gateway网关,通过检查请求地址匹配相应的服务请求,访问时直接请求网关的请求地址,会转发到相应的服务;可通过yml文件配置或者代码配置
pom:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency>
gateway的yml配置:
spring: application: name: cloud-gateway cloud: gateway: discovery: locator: enabled: true # 开启从注册中心动态创建路由的功能,利用微服务名称j进行路由 routes: - id: payment_route # 路由的id,没有规定规则但要求唯一,建议配合服务名 #匹配后提供服务的路由地址 # uri: http://localhost:8001 固定地址 uri: lb://cloud-payment-service # 服务名 predicates: # 过滤 - Path=/payment/get/** # 断言,路径相匹配的进行路由 - After=2021-11-01T10:01:53.212+08:00[Asia/Shanghai] #- 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 predicates: Path=/payment/lb/** #断言,路径相匹配的进行路由
代码文件指定转发的接口(代码配置)
package com.atguigu.springcloud.config; import org.springframework.cloud.gateway.route.RouteLocator; import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class GatewayConfig { @Bean public RouteLocator customRouteLocator(RouteLocatorBuilder routeLocatorBuilder){ RouteLocatorBuilder.Builder routers = routeLocatorBuilder.routes(); routers.route("path_route_atguigu", r ->r.path("/guonei") .uri("http://news.baidu.com/guonei")).build(); return routers.build(); } }
配置过滤条件
package com.atguigu.springcloud.config.filter; import lombok.extern.slf4j.Slf4j; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.core.Ordered; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; import java.util.Date; @Component @Slf4j public class MyLogGateWayFilter implements GlobalFilter, Ordered { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { log.info("********MyLogGateWayFilter"+new Date()); String uname = exchange.getRequest().getQueryParams().getFirst("uname"); if(uname == null){ log.info("非法用户"); exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE); return exchange.getResponse().setComplete(); } return chain.filter(exchange); } @Override public int getOrder() { return 0; } }
标签:配置,springframework,详解,路由,org,import,gateway,cloud From: https://www.cnblogs.com/brandon-i/p/17102570.html