GateWay 的使用
介绍
GateWay网关技术用于取代ruul1.x
环境配置
网关不需要业务类
pom依赖
注意:gateway 模块中不要带有 spring web、spring author 依赖,否则会报错,因为网关不需要这些依赖
org.springframework.cloud
spring-cloud-starter-gateway
主启动类
示例中我使用了 Eureka,所以我们把gateway网关也加进Eureka集群中
yaml配置文件
正常配置端口号、微服务名、Eureka即可(示例中我使用了Eureka集群)
server:
port: 9527
spring:
application:
name: cloud-gateway
eureka:
instance:
hostname: cloud-gateway-service
client: #服务提供者provider注册进eureka服务列表内
service-url:
register-with-eureka: true
fetch-registry: true
defaultZone: http://eureka7001.com:7001/eureka
入门1:yaml配置方式
我们网关的端口号是:9527,这段配置文件的意思是:当我们访问localhost:9527/payment/get/1时,会跳转到http://localhost:8001/payment/get/1 请求,这种规则可以配置多个,详情看配置文件
配置文件中的**是通配符
cloud:
gateway:
routes:
- id: payment_routh #payment_route #路由的ID,没有固定规则但要求唯一,建议配合服务名
uri: http://localhost:8001 #匹配后提供服务的路由地址
predicates:
- Path=/payment/get/** # 断言,路径相匹配的进行路由
- id: payment_routh2 #payment_route #路由的ID,没有固定规则但要求唯一,建议配合服务名
uri: http://localhost:8001 #匹配后提供服务的路由地址
predicates:
- Path=/payment/lb/** # 断言,路径相匹配的进行路由
以上代码是添加的部分,完整yaml示例如下:
server:
port: 9527
spring:
application:
name: cloud-gateway
cloud:
gateway:
routes:
- id: payment_routh #payment_route #路由的ID,没有固定规则但要求唯一,建议配合服务名
uri: http://localhost:8001 #匹配后提供服务的路由地址
predicates:
- Path=/payment/get/** # 断言,路径相匹配的进行路由
- id: payment_routh2 #payment_route #路由的ID,没有固定规则但要求唯一,建议配合服务名
uri: http://localhost:8001 #匹配后提供服务的路由地址
predicates:
- Path=/payment/lb/** # 断言,路径相匹配的进行路由
eureka:
instance:
hostname: cloud-gateway-service
client: #服务提供者provider注册进eureka服务列表内
service-url:
register-with-eureka: true
fetch-registry: true
defaultZone: http://eureka7001.com:7001/eureka
入门2:bean注入方式
功能与入门1相同
创建配置类,Bean注入即可,如果需要多个映射,需要注入多个bean
@Bean
public RouteLocator customRouteLocator2(RouteLocatorBuilder builder)
{
RouteLocatorBuilder.Builder routes = builder.routes();
routes.route("id",
r -> r.path("/guonei").uri("http://news.baidu.com/guonei")).build();
return routes.build();
}
代码的意思是,访问网关地址/guonei时会映射到http://news.baidu.com/guonei请求
配置动态路由(微服务名访问)
上面的示例localhost:8001这类地址写的太死了
一般都是直接用微服务名访问,这样也能负载均衡
改一些yaml即可,如图
Predicate 的使用
实在太多了,这里引用这位大佬的博文
过滤器
另起一篇