问题描述
我已经实现了zuul网关服务,用于我编写的一些微服务之间的通信.我有一个特定的场景,例如我想在我的自定义过滤器之一中更改服务路径,然后重定向到其他服务. zuul网关有可能吗?我尝试将带有更新的uri的"requestURI"参数放入路由过滤器中的请求上下文中,但效果不佳
I have implemented a zuul gateway service for the communication between some micro services that i have wrote. I have a specific scenario like i want to change the service path in one of my custom filter and redirected to some other service. Is this possible with the zuul gateway?. I have tried putting "requestURI" parameter with the updated uri to the request context in my route filter but that didn't worked out well
请帮帮我预先感谢
推荐答案
是的,可以.为此,您需要实现类型为PRE_TYPE
的ZuulFilter
,并使用指定的Location
标头和响应状态为301或302更新响应.
yes, you can. for that you need to implement ZuulFilter
with type PRE_TYPE
, and update response with specified Location
header and response status either 301 or 302.
@Slf4j
public class CustomRedirectFilter extends ZuulFilter {
@Override
public String filterType() {
return FilterConstants.PRE_TYPE;
}
@Override
public int filterOrder() {
return FilterConstants.SEND_FORWARD_FILTER_ORDER;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
String requestUrl = ctx.getRequest().getRequestURL().toString();
if (shouldBeRedirected(requestUrl)) {
String redirectUrl = generateRedirectUrl(ctx.getRequest());
sendRedirect(ctx.getResponse(), redirectUrl);
}
return null;
}
private void sendRedirect(HttpServletResponse response, String redirectUrl){
try {
response.setHeader(HttpHeaders.LOCATION, redirectUrl);
response.setStatus(HttpStatus.MOVED_PERMANENTLY.value());
response.flushBuffer();
} catch (IOException ex) {
log.error("Could not redirect to: " + redirectUrl, ex);
}
}
private boolean shouldBeRedirected(String requestUrl) {
// your logic whether should we redirect request or not
return true;
}
private String generateRedirectUrl(HttpServletRequest request) {
String queryParams = request.getQueryString();
String currentUrl = request.getRequestURL().toString() + (queryParams == null ? "" : ("?" + queryParams));
// update url
return updatedUrl;
}
}
这篇关于在Zuul网关中,如何在自定义过滤器中修改服务路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!