【问题标题】:Spring Cloud : Using routing type filter in ZuulSpring Cloud:在 Zuul 中使用路由类型过滤器
【发布时间】:2017-06-17 11:52:31
【问题描述】:

我有 2 个使用 Spring Boot 构建的微服务(服务 A 和服务 B),它们通过同样构建为 Spring Boot 应用程序的 Zuul 代理进行路由,我检查了 Zuul 代理是否工作正常。但是,我要做的是编写一个自定义路由类型 ZuulFilter,当对服务 B 的请求进入时,它应该首先路由到服务 A。这是我需要帮助的:

  1. 我想知道一个路由过滤器的外观示例,因为我在搜索 Internet 后没有看到任何内容。我得到的是一些预过滤器的例子,Netflix's documentation 在这方面没有多大帮助。

  2. 编写自定义路由过滤器是否会打乱Zuul原有的路由行为

【问题讨论】:

  • 所以...Zuul 调用服务 A,然后代理服务 B,或者 Zuul 先调用服务 A,一旦请求完成,Zuul 调用服务 B?
  • 因此,请求来自 Zuul 代理的服务 B,但使用 ZuulFilter,服务 A 被调用,并根据其响应服务 B 应由 Zuul 代理。

标签: spring-boot spring-cloud netflix-zuul


【解决方案1】:

我会在 Zuul 过滤器中构造一个 Feign client 并使用它调用服务 A。 Feign 将填充功能区负载平衡器,以与 Zuul 在代理时所做的相同方式进行调用。

【讨论】:

  • 只是为了进一步理解,所以 Feign 客户端会调用 Zuul 为服务 A 提供的端点,因为服务 A 可能有多个实例,对吗?如果是,那么与允许 Zuul 中的某些配置在其自身内部自动路由相比,这不是开销吗?
  • feign 客户端从 Zuul 使用的同一发现客户端(源自 Eureka)填充其功能区负载均衡器,所以是的,它们有效地使用相同的源和相同的负载均衡调用底层方法。
  • 您能否提供一些示例以帮助我了解路由的工作原理?
  • 我通过构建一个 Feign 客户端使其工作,该客户端本身使用服务发现来查找我打算从 Zuul 过滤器调用的服务 A 的实例
【解决方案2】:

我遇到了同样的问题,这就是我想出的。

public class ServicesLegacyRouteFilter extends ZuulFilter {

    private ServiceB serviceB;

    public ServiceLegacyRouteFilter(ServiceB serviceB) {
        this.serviceB = serviceB;
    }

    @Override
    public String filterType() {
        return ROUTE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {

        RequestContext ctx = RequestContext.getCurrentContext();

        if ("serviceA".equals(ctx.get("serviceId"))) {

            //call Service B here and use return type to set
            //the final destination service
            String destination = serviceB.routeWhere();
            ctx.set("serviceId", destination);

            return true;
        }

        return false;
    }

    @Override
    public Object run() {

        RequestContext ctx = RequestContext.getCurrentContext();

        // Or call ServiceB here to make your determination on
        // the final destination.

        String destination = serviceB.routeWhere();
        ctx.set("serviceId", destination);


        return null;
    }
}

当然,我的实际生产用例在路由上更复杂,但这是我如何能够根据输入的内容更改路由以及如何利用 Zuul 将其输出到正确的基础知识服务。

【讨论】:

  • 我认为这个解决方案与我的问题无关。我的问题更多是基于服务 B 作为是否调用服务 A 的决策者。纠正我,如果我理解你的解决方案不正确。
  • 路由过滤器可用于在 shouldFilter 方法或 run 方法中调用服务 B 以确定设置的实际目的地。我将尝试编辑我的回复以使其更清晰。
  • ServiceB 类类型是如何定义的,它是如何在构造函数中传递/注入的?这至少作为@EnableConfigurationProperties(...) 类不是更好吗?
猜你喜欢
  • 2016-05-27
  • 2017-09-03
  • 2016-07-11
  • 2020-04-15
  • 2018-08-23
  • 2023-03-04
  • 2020-04-29
  • 2016-08-31
  • 2017-12-02
相关资源
最近更新 更多