当前位置:

GatewayGateway网关路由有两种配置方式

访客 2024-02-04 1374 0

1.yml配置

spring:application:name:cloud-gatewaycloud:gateway:discovery:locator:enabled:true#开启从注册中心动态创建路由的功能,利用微服务名进行路由routes:-id:payment_routh#payment_route#路由的ID,没有固定规则但要求唯一,建议配合服务名#uri:http://localhost:8001#匹配后提供服务的路由地址uri:lb://cloud-payment-service#匹配后提供服务的路由地址predicates:-Path=/payment/get/**#断言,路径相匹配的进行路由-id:payment_routh2#payment_route#路由的ID,没有固定规则但要求唯一,建议配合服务名#uri:http://localhost:8001#匹配后提供服务的路由地址uri:lb://cloud-payment-service#匹配后提供服务的路由地址predicates:-Path=/payment/lb/**#断言,路径相匹配的进行路由#-After=2020-02-21T15:51:37.48508:00[Asia/Shanghai]#-Cookie=username,zzyy#-Header=X-Request-Id,\d#请求头要有X-Request-Id属性并且值为整数的正则表达式

2.编写配置类(代码中注入RouteLocator的Bean)

@ConfigurationpublicclassGateWayConfig{/***配置了一个id为path_route_atguigu的路由规则,*当访问地址http://localhost:9527/guonei时会自动转发到地址:http://news.百度.com/guonei*@param*@return*/@BeanpublicRouteLocatorcustomRouteLocator(RouteLocatorBuilderrouteLocatorBuilder){/*相当于额yml配置中的routes*/RouteLocatorBuilder.Builderroutes=routeLocatorBuilder.routes();/*id就是yml中的id*///这是想路由的网址:http://news.百度.com/guoneiroutes.route("path_route_atguigu",r->r.path("/guonei").uri("http://news.百度.com/guonei")).build();returnroutes.build();}/***配置了一个id为path_route_atguigu2的路由规则,*当访问地址http://localhost:9527/guoji时会自动转发到地址:http://news.百度.com/guonei*@param*@return*/@BeanpublicRouteLocatorcustomRouteLocator2(RouteLocatorBuilderbuilder){RouteLocatorBuilder.Builderroutes=builder.routes();routes.route("path_route_atguigu2",r->r.path("/guoji").uri("http://news.百度.com/guoji")).build();returnroutes.build();}}

发表评论

  • 评论列表
还没有人评论,快来抢沙发吧~