Skip to content

如何自定义实现基于域名前缀的环境路由隔离

HaojunRen edited this page May 31, 2024 · 8 revisions

实现基于域名前缀的环境路由隔离的功能,需要继承RouteFilter

下面代码既适用于Spring Cloud Gateway和Zuul网关,也适用于微服务,继承DefaultGatewayStrategyRouteFilter、DefaultZuulStrategyRouteFilter和DefaultServiceStrategyRouteFilter,覆盖掉目标方法,通过@Bean方式覆盖框架内置的过滤类

Spring Cloud Gateway网关过滤器

public class MyGatewayStrategyRouteFilter extends DefaultGatewayStrategyRouteFilter {
    private static final Logger LOG = LoggerFactory.getLogger(MyGatewayStrategyRouteFilter.class);

    @Autowired
    private GatewayStrategyContextHolder gatewayStrategyContextHolder;

    // 自定义根据域名全链路环境隔离
    @Override
    public String getRouteEnvironment() {
        String host = gatewayStrategyContextHolder.getURI().getHost();
        if (host.contains("nepxion.com")) {
            LOG.info("自定义根据域名全链路环境隔离, URL={}", host);

            String environment = host.substring(0, host.indexOf("."));

            LOG.info("执行全链路环境隔离={}", environment);

            return environment;
        }

        return super.getRouteEnvironment();
    }
}

在配置类里@Bean方式进行过滤类创建,覆盖框架内置的过滤类

@Bean
public GatewayStrategyRouteFilter gatewayStrategyRouteFilter() {
    return new MyGatewayStrategyRouteFilter();
}

本地测试,为验证结果,请事先在hosts文件中配置如下

127.0.0.1 common.nepxion.com
127.0.0.1 env1.nepxion.com
127.0.0.1 env2.nepxion.com
  • 根据env1.nepxion.com域名路由到env1环境

  • 根据common.nepxion.com域名路由到common环境

Zuul网关过滤器

只需要把上述代码extends DefaultGatewayStrategyRouteFilter换成extends DefaultZuulStrategyRouteFilter,用法、功能和代码则基本一致

微服务过滤器

只需要把上述代码extends DefaultGatewayStrategyRouteFilter换成extends DefaultServiceStrategyRouteFilter,用法、功能和代码则基本一致




2017-2050 ©Nepxion Studio Apache License

           

Total visits

讲义篇

集成篇

概念篇

实践篇

功能篇

配置篇

扩展篇

测试篇

升级篇

贡献篇

Clone this wiki locally