网关统一服务入口,主要用于身份认证、业务鉴权、防数据篡改、响应数据脱敏等
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency>
spring: application: name: illriver-bbs-gateway cloud: gateway: routes: - id: goods_route uri: http://localhost:31007 predicates: - Path=/product/**
可以设置不同断言实现不同条件路由转发规则,详见官方文档:
https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/
@Configuration public class RouteConfig { @Bean public RouteLocator routes(RouteLocatorBuilder builder){ return builder.routes() .route("goods_route",r->r.path("/product/**").uri("http://localhost:31003")) .build(); } }
management: endpoints: web: exposure: include: "*" #暴露路由规则web站点 /actuator/gateway/routes
spring: application: name: illriver-bbs-gateway cloud: gateway: routes: - id: goods_route uri: lb://illriver-bbs-goods predicates: - Path=/product/** discovery: locator: enabled: true #开启根据服务名动态获取路由地址
spring: application: name: illriver-bbs-gateway cloud: gateway: routes: - id: goods_route uri: lb://illriver-bbs-goods predicates: - Path=/product/** filters: - AddRequestParameter=productId, 45 - AddResponseHeader=color, blue
更多默认提供filer详见官方文档。
@Configuration @Slf4j public class CustomGlobalFiler implements GlobalFilter, Ordered { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { if (exchange.getRequest().getQueryParams().get("userName") != null){ return chain.filter(exchange); } return exchange.getResponse().setComplete(); } @Override public int getOrder() { return 0; } }