Skip to content

Spring Cloud Gateway - 网关动态路由实现方案总结 #21

@TFdream

Description

@TFdream

动态路由背景

在使用 Cloud Gateway 的时候,官方文档提供的方案有2种:

  • 基于yml配置
  • 硬编码

这两种方式都是不支持动态刷新路由配置的。

基于配置文件配置的方式,例如:

spring:
      routes:
        - id: auth
          uri: ${gateway.route.url.uaa-service}
          predicates:
            - Path=/api-uaa/**
          filters:
            - StripPrefix=1
            - PreserveHostHeader
        - id: auth-login-page
          uri: ${gateway.route.url.uaa-service}
          predicates:
            - Path=/login.html
          filters:
            - PreserveHostHeader

代码配置如下:

@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>.*)", "/${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();
	}
}

以上两种方式 配置更改后需要重启服务才能生效,不能满足实际生产过程中的动态刷新、实时变更的业务需求。

:本篇 Spring Boot版本为 2.3.0.RELEASE,Spring Cloud版本为Hoxton.SR5,spring-cloud-gateway版本为2.2.3.RELEASE。

思路

参考资料

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions