问题描述
如何基于 HTTP方法(GET/POST/PUT ...)使Zuul动态路由?例如,当您需要将 POST 请求路由到不同的主机而不是" zuul.routes.* "中描述的默认请求时. ...
How to make Zuul dynamic routing based on HTTP method (GET/POST/PUT...)?For example, when you need to route the POST request to the different host instead of the default one described in '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将请求路由到'第一服务',但是如果我们请求' POST/first ",然后Zuul将请求路由到"第二项服务".
I.e. when we request 'GET /first' then Zuul route the request to the 'first-service', but if we request 'POST /first' then Zuul route the request to the 'second-service'.
推荐答案
要实现基于HTTP方法的动态路由,我们可以创建自定义的' 路由 ",键入ZuulFilter
并通过DiscoveryClient
解析"serviceId".例如:
To implement dynamic routing based on HTTP method we can create a custom 'route' type ZuulFilter
and resolve 'serviceId' through DiscoveryClient
. Fore example:
@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;
}
}
这篇关于如何使基于HTTP方法的Zuul动态路由和通过"serviceId"解析目标主机?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!