其他分享
首页 > 其他分享> > spring – 如何基于HTTP方法进行Zuul动态路由,并通过’serviceId’解析目标主机?

spring – 如何基于HTTP方法进行Zuul动态路由,并通过’serviceId’解析目标主机?

作者:互联网

如何基于HTTP方法(GET / POST / PUT …)进行Zuul动态路由?
例如,当您需要将POST请求路由到不同的主机而不是’zuul.routes.*’中描述的默认主机时…

zuul:
  routes:
    first-service:
      path: /first/**
      serviceId: first-service
      stripPrefix: false

    second-service:
      path: /second/**
      serviceId: second-service
      stripPrefix: false

即当我们请求’GET / first’时,Zuul将请求路由到’first-service’,但是如果我们请求’POST / first’,那么Zuul将请求路由到’second-service’.

解决方法:

要实现基于HTTP方法的动态路由,我们可以创建自定义’route‘类型ZuulFilter并通过DiscoveryClient解析’serviceId’.例如:

@Component
public class PostFilter extends ZuulFilter {

    private static final String REQUEST_PATH = "/first";
    private static final String TARGET_SERVICE = "second-service";
    private static final String HTTP_METHOD = "POST";

    private final DiscoveryClient discoveryClient;

    public PostOrdersFilter(DiscoveryClient discoveryClient) {
        this.discoveryClient = discoveryClient;
    }

    @Override
    public String filterType() {
        return "route";
    }

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

    @Override
    public boolean shouldFilter() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String method = request.getMethod();
        String requestURI = request.getRequestURI();
        return HTTP_METHOD.equalsIgnoreCase(method) && requestURI.startsWith(REQUEST_PATH);
    }

    @Override
    public Object run() {

        RequestContext context = RequestContext.getCurrentContext();
        List<ServiceInstance> instances = discoveryClient.getInstances(TARGET_SERVICE);
        try {
            if (instances != null && instances.size() > 0) {
                context.setRouteHost(instances.get(0).getUri().toURL());
            } else {
                throw new IllegalStateException("Target service instance not found!");
            }
        } catch (Exception e) {
            throw new IllegalArgumentException("Couldn't get service URL!", e);
        }
        return null;
    }
}

标签:spring-cloud-netflix,spring,netflix-zuul,spring-cloud
来源: https://codeday.me/bug/20190828/1749239.html