首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >运行时修改Spring Cloud Gateway路由

运行时修改Spring Cloud Gateway路由
EN

Stack Overflow用户
提问于 2020-10-01 20:48:00
回答 2查看 872关注 0票数 0

我想要在服务器运行时添加或删除Spring Cloud Gateway路由。我正在使用Fluent Java Routes API初始化网关路由。这是完美的工作。

但是,现在我想在Spring Cloud Gateway服务器运行时修改、添加和删除路由。我可以看到RouteLocator包含我的路由,但我看不到修改其内容的方法。

尽管我在执行器中看到了一些添加功能,但我需要使用create new routes代码来添加它们,而不是REST调用。在我的设置中,RouteDefinitionRepository是空的,所以我看不到在我的用例中使用它的任何方法。

在Spring Cloud Gateway中,是否可以在运行时仅使用Java代码修改路由?

EN

回答 2

Stack Overflow用户

发布于 2020-10-15 02:21:23

请改用Spring Integration。您可以使用Java DSL注册和删除集成流。https://docs.spring.io/spring-integration/docs/5.3.2.RELEASE/reference/html/dsl.html#java-dsl-runtime-flows

票数 0
EN

Stack Overflow用户

发布于 2021-01-14 21:55:41

我做了一些类似的删除路由的事情,向网关隐藏服务。尝试实例化一个自定义RouteLocator,如下所示:

代码语言:javascript
复制
@Configuration
public class RouteConfiguration implements CommandLineRunner {

    final Logger LOGGER = LoggerFactory.getLogger(RouteConfiguration.class);

    @Value("${route.ignore.service-ids}")
    private String[] ignoreServiceIds;

    @Override
    public void run(String... args) throws Exception {

        if(ignoreServiceIds != null){
            for(String s: ignoreServiceIds){
                LOGGER.info("ServiceID ignored: {}",s);
            }
        }
    }

    @Bean
    @Primary
    @ConditionalOnMissingBean(name = "cachedCompositeRouteLocator")
    public RouteLocator cachedCompositeRouteLocator(List<RouteLocator> routeLocators) {

        return new CachingRouteLocator(new CustomCompositeRouteLocator(Flux.fromIterable(routeLocators), ignoreServiceIds));
    }
}

然后应用过滤器:

代码语言:javascript
复制
public class CustomCompositeRouteLocator implements RouteLocator {

    private final Flux<RouteLocator> delegates;
    private List<String> ignoredServiceIds;

    public CustomCompositeRouteLocator(Flux<RouteLocator> delegates, String[] ignoreServiceIds) {
        this.delegates = delegates;

        if(ignoreServiceIds != null && ignoreServiceIds.length>0)
            this.ignoredServiceIds = List.of(ignoreServiceIds);
    }

    @Override
    public Flux<Route> getRoutes() {

        if(ignoredServiceIds == null || ignoredServiceIds.isEmpty())
            return this.delegates.flatMapSequential(RouteLocator::getRoutes);
        return this.delegates.flatMapSequential(RouteLocator::getRoutes).filter(p->!ignoredServiceIds.contains(p.getUri().getHost()));
    }
}

application.yaml

代码语言:javascript
复制
...
route:
  ignore:
    service-ids: MY_IGNORED_SERVICE_ID
...
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64155739

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档