gateway的默认路由规则
添加依赖(注意:是eureka-client)
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
规则:http://Gateway_HOST:Gateway_PORT/大写的serviceId/**
其中微服务应用名默认大写访问。
实例代码:
分别新建上面这四个服务,详见 spring cloud Finchley环境搭建
其中gateway-service服务的application.yml配置文件如下:
spring:
application:
name: gateway-service
cloud: # spring cloud gateway 路由配置方式
gateway:
discovery: #是否与服务发现组件进行结合,通过 serviceId(必须设置成大写) 转发到具体的服务实例。默认为false,设为true便开启通过服务中心的自动根据 serviceId 创建路由的功能。
locator: #路由访问方式:http://Gateway_HOST:Gateway_PORT/大写的serviceId/**,其中微服务应用名默认大写访问。
enabled: true
routes:
- id: 163 #网关路由到网易官网
uri: http://www.163.com/
predicates:
- Path=/163/**
# - id: ORDER-SERVICE #网关路由到订单服务order-service
# uri: lb://ORDER-SERVICE
# predicates:
# - Path=/ORDER-SERVICE/**
# - id: USER-SERVICE #网关路由到用户服务user-service
# uri: lb://USER-SERVICE
# predicates:
# - Pach=/USER-SERVICE/**
server:
port: 5001
logging:
level:
org.springframework.cloud.gateway: trace
org.springframework.http.server.reactive: debug
org.springframework.web.reactive: debug
reactor.ipc.netty: debug
eureka:
client:
service-url:
defaultZone: http://localhost:5000/eureka/
feign:
hystrix:
enabled: true
配置项说明:
- spring.cloud.gateway.discovery.locator.enabled:是否与服务发现组件进行结合,通过 serviceId 转发到具体的服务实例。默认为false,设为true便开启通过服务中心的自动根据 serviceId 创建路由的功能。
- eureka.client.service-url.defaultZone: http://localhost:5000/eureka/,指定注册中心的地址,Spring Cloud Gateway从注册中心获取已经注册的服务列表。
- logging.level.org.springframework.cloud.gateway: debug,开启spring-Cloud-gateway的日志级别为debug,方便debug调试。
启动测试
1 )错误的路由规则访问
访问Spring Cloud Gateway对应的server,当访问http://localhost:5000/order-service/order/getOrderPort的时候,会出现报错内容如下所示:
正确的Spring Cloud Gateway的默认路由规则:http://Gateway_HOST:Gateway_PORT/大写的serviceId/**
2)Gateway正确的路由规则测试