eureka上的微服务不能通过服务名调用_Spring Cloud Gateway基于服务发现的默认路由规则-Part 3...

Spring Cloud Gateway核心概念和工作原理-Part 1

Spring Cloud Gateway的路由断言(Predicate)-Part 2

Spring Cloud Gateway是Spring官方基于Spring 5.0,Spring Boot 2.0和Project Reactor等技术开发的网关,Spring Cloud Gateway旨在为微服务架构提供一种简单而有效的统一的API路由管理方式。Spring Cloud Gateway作为Spring Cloud生态系中的网关,目标是替代Netflix ZUUL,其不仅提供统一的路由方式,并且基于Filter链的方式提供了网关基本的功能,例如:安全,监控/埋点,和限流等。

4ebe978f68f27ac45fef749dc86a5ab3.png

基于服务发现的默认路由规则

Gateway基于服务发现的路由规则和Zuul的设计类似,但也有差别。

如果把Gateway 注册到Eureka上,通过网关转发服务调用时,默认需要大写的serviceId/*,服务名默认必须大写,否则会出现404错误。如果需要使用小写的服务名(如Zuul 网关),可以在配置文件中添加spring.cloud.gateway.discovery.locator.lowerCaseServiceId=true 来配置解决。

1. 在Spring Cloud Gateway 项目中,添加如下依赖。

其中添加actuator jar 包,是为了查看Spring Cloud Gateway 自动为服务消费者创建的路由信息。

引入 eureka-client jar包,是为了让gateway 注册到Eureka Server上。

org.springframework.cloud

spring-cloud-starter-gateway

org.springframework.cloud

spring-cloud-starter-netflix-eureka-client

org.springframework.boot

spring-boot-starter-actuator

2. 创建application.yml 配置文件

spring:

application:

name: sc-gateway-server

cloud:

gateway:

discovery:

locator:

enabled: true

#lowerCaseServiceId: true

server:

port: 9000 #网关服务监听 9000 端口

eureka:

client:

service-url: #指定注册中心的地址,以便使用服务发现功能

defaultZone: http://localhost:8761/eureka/

logging:

level: #调整相关包的 log 级别,以便排查问题

org.springframework.cloud.gateway: debug

management:

endpoints:

web:

exposure:

include: '*'

security:

enabled: false

其中配置项说明:

spring.cloud.gateway.discovery.locator.enabled = true (默认为false) 开启基于服务发现的默认路由规则,可以通过serviceId 转发到具体的服务实例。

spring.cloud.gateway.discovery.locator.lowerCaseServiceId = true(默认为false)当注册中心为 Eureka时,设置为 true表示开启小写的serviceId 进行基于服务路由的转发。

logging.level 设置相关包的 log 级别,方便排查问题。

3. 启动应用测试

演示项目中,包括Eureka,Gateway,ServiceProvider,ServiceConsumer等等应用。

e4a3c4e706f0a0b89e9f409fc8d5ea64.png

访问 http://localhost:9000/sc-consumer/hello/rickie

可以成功进行转发,调用服务提供者。

ce5e417ba5df50a11f3a702ab01b66fe.png

访问 http://localhost:9000/actuator/gateway/routes

查看返回的路由信息。看到Spring Cloud Gateway 自动添加的路由信息。

8580d954e803c81c6edb3ea1a072bec6.png

当把 spring.cloud.gateway.discovery.locator.lowerCaseServiceId = true 注释掉,默认为 false。

此时,访问 http://localhost:9000/sc-consumer/hello/rickie,就会出现 404 错误。

5694a1e35f1a0dec9a399704a97270ec.png

访问 http://localhost:9000/actuator/gateway/routes

查看返回的路由信息。看到Spring Cloud Gateway 自动添加的路由信息。此时发现serviceId 需要大写,才能正确路由转发。

http://localhost:9000/SC-CONSUMER/hello/rickie

4369923f6b48395f23facfd246474b23.png

完整的演示项目代码:

https://github.com/rickiechina/spring-cloud-code/tree/master/ch18-1

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值