本文共 1758 字,大约阅读时间需要 5 分钟。
Spring Cloud Gateway是Spring Cloud官方推出的第二代网关框架,取代Zuul网关。网关作为流量的,在微服务系统中有着非常作用,网关常见的功能有路由转发、权限校验、限流控制等作用。
在Spring Cloud Gateway中有2个重要的概念Predicat
和Filter
。 Predicat作为断言,它决定了请求会被路由到哪个router 中。在断言之后,请求会被进入到Filter过滤器的逻辑。 导入依赖
org.springframework.cloud spring-cloud-starter-gateway org.springframework.cloud spring-cloud-starter-netflix-eureka-client
添加application.yml
配置信息
server: port: 8087spring: application: name: gateway cloud: gateway: discovery: locator: # 开启服务注册和发现的功能 enabled: true # 请求路径上的服务名配置为小写 lower-case-service-id: trueeureka: client: serviceUrl: defaultZone: http://localhost:9100/eureka/
经过上面的配置gateway网关会将/eureka-client/*
的请求路径被路由转发到服务名为eureka-client
的服务上。
eureka-client
这个前缀,才能转发到eureka-client
上,转发之前会将eureka-client
去掉。 比如http://127.0.0.1:8087/eureka-client/hello
会转发到http://eureka-client/hello
地址上。 自定义路径并转发到具体的服务上,修改配置文件application.yml
spring: application: name: gateway cloud: gateway: discovery: locator: enabled: false lower-case-service-id: true routes: - id: eureka-client uri: lb://EUREKA-CLIENT predicates: - Path=/demo/** filters: - StripPrefix=1 - id: eureka-client2 uri: lb://EUREKA-CLIENT2 predicates: - Path=/demo2/** filters: - StripPrefix=1
配置了一个Path的predict
,将以/demo/**
开头的请求都会转发到uri
为lb://EUREKA-CLIENT
的地址上,lb://EUREKA-CLIENT
即eureka-client
服务的负载均衡地址,并用StripPrefix
的filter在转发之前将/demo去掉。同时将spring.cloud.gateway.discovery.locator.enabled
改为false,如果不改的话,之前的http://127.0.0.1:8087/eureka-client/hello
这样的请求地址也能正常访问,因为这时为每个服务创建了2个router。
转载地址:http://agdhb.baihongyu.com/