如标题所示,在spring cloud gateway 配置路由转发的过程中,通常会使用到以下两种方式的路由配置方式:
1、基于配置文件的方式(个人使用的是yml格式的配置文件,因为看起来更直观)
2、工程中hard code的形式。
基于配置文件的方式
话不多说,直接上图
spring:
application:
name: cloud-gateway
profiles:
active: dev
################################################################spring cloud gateway##############################################################
cloud:
gateway:
discovery:
locator:
enabled: false #当访问http://网关地址/服务名称(大写)/**地址会自动转发到http://服务名称(大写)/**地址,如果为false就不会自动转发
lowerCaseServiceId: false #为true表示服务名称(小写)
routes:
- id: cloud-provider-payment #路由id,需要全局统一,建议使用对应的spring.application.name
uri: http://localhost:8001 #路由到对应服务的地址
predicates:
- Path=/service/**/* #断言,匹配规则,ant匹配
############################################################
- id: cloud-provider-payment2 #路由id,需要全局统一,建议使用对应的spring.application.name
uri: http://localhost:8002 #路由到对应服务的地址
predicates:
- Path=/service/**/* #断言,匹配规则,ant匹配
配置项的各涵义已在注释中加以说明。当做完以上配置的时候,启动服务,并且在org.springframework.cloud.gateway.config.GatewayProperties类的第64行打上断点
可以很清晰明了地看出,配置项中填入的多个路由配置,已经被注入到了对应的Spring容器中。 接着,我们就可以通过访问网关的形式,让网关替我们转发请求至对应的服务中去。
http(s)://{GATEWAY_HOST}/cloud-provider-payment/service/**/*
这里需要注意的是,当我们在网关地址后面,使用服务名称做自动路由的时候,需要将以下两个配置开关打开:
spring:
################################################################spring cloud gateway##############################################################
cloud:
gateway:
discovery:
locator:
enabled: true #当访问http://网关地址/服务名称(大写)/**地址会自动转发到http://服务名称(大写)/**地址,如果为false就不会自动转发
lowerCaseServiceId: true #为true表示服务名称(小写)
工程中hard code的形式
/**
* 路由到外部
*
* @return
*/
@Bean
public RouteLocator externalRouteLocator(RouteLocatorBuilder builder) {
RouteLocatorBuilder.Builder routes = builder.routes();
//跳转到百度新闻国内栏目
routes.route("news", (r) ->
r.path("/guonei").
uri("http://news.baidu.com/guonei")).build();
return routes.build();
}
这是一个简单的示例,更多示例可以参考上官网上的Getting Started
@SpringBootApplication
public class DemogatewayApplication {
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("path_route", r -> r.path("/get")
.uri("http://httpbin.org"))
.route("host_route", r -> r.host("*.myhost.org")
.uri("http://httpbin.org"))
.route("rewrite_route", r -> r.host("*.rewrite.org")
.filters(f -> f.rewritePath("/foo/(?.*)", "/${segment}"))
.uri("http://httpbin.org"))
.route("hystrix_route", r -> r.host("*.hystrix.org")
.filters(f -> f.hystrix(c -> c.setName("slowcmd")))
.uri("http://httpbin.org"))
.route("hystrix_fallback_route", r -> r.host("*.hystrixfallback.org")
.filters(f -> f.hystrix(c -> c.setName("slowcmd").setFallbackUri("forward:/hystrixfallback")))
.uri("http://httpbin.org"))
.route("limit_route", r -> r
.host("*.limited.org").and().path("/anything/**")
.filters(f -> f.requestRateLimiter(c -> c.setRateLimiter(redisRateLimiter())))
.uri("http://httpbin.org"))
.build();
}
}