配置方式实现Zuul动态路由
Zuul路由信息可以来自Properties文件、DB、Apollo等。
zuul:
host:
connect-timeout-millis: 3000
socket-timeout-millis: 20000
routes:
unified:
path: /gw/**
serviceId: gw
sensitiveHeaders:
routes:
services:
union_pay_online: ok-cloud-union-pay-online
union_pay_offline: ok-cloud-union-pay-offline
@Data
@Configuration
@ConfigurationProperties(prefix = "routes")
public class RouteConfig {
@NestedConfigurationProperty
private Map<String, String> services = new HashMap<>();
}
@Slf4j
@Component
public class RouteFilter extends ZuulFilter {
@Autowired
RouteConfig routeConfig;
@Override
public Object run() throws ZuulException {
RequestContext ctx = RequestContext.getCurrentContext();
if (!ctx.sendZuulResponse()) {
return null;
}
HttpServletRequest request = ctx.getRequest();
log.info("请求uri: {}", request.getRequestURI());
Object originalRequestPath = ctx.get(FilterConstants.REQUEST_URI_KEY);
log.info("originalRequestPath = {}", originalRequestPath);
try {
String serviceCode = request.getParameter("service_code");
if (isBlank(serviceCode)) {
String requestBody = StreamUtils.copyToString(request.getInputStream(), Charset.forName(CharEncoding.UTF_8));
ServiceDto dto = JSON.parseObject(requestBody, ServiceDto.class);
serviceCode = dto.getProduct_code();
}
if (isBlank(serviceCode)) {
sendErrorResponse(ResultBuilder.failure(ResponseCode.BAD_REQUEST.code(), "service_code is blank"));
return null;
}
String serviceId = routeConfig.getServices().get(serviceCode.toLowerCase());
ctx.put(FilterConstants.SERVICE_ID_KEY, serviceId);
ctx.put(FilterConstants.PROXY_KEY, serviceId);
//ctx.put(REQUEST_URI_KEY, route.getPath());
} catch (Exception e) {
log.error("", e);
sendErrorResponse(ResultBuilder.failure(ResponseCode.SERVICE_UNAVAILABLE));
}
return null;
}
private void sendErrorResponse(Result result) {
RequestContext requestContext = RequestContext.getCurrentContext();
requestContext.setSendZuulResponse(false);
requestContext.addZuulResponseHeader("Content-type", "application/json;charset=UTF-8");
requestContext.setResponseBody(JSON.toJSONString(result));
}
@Override
public String filterType() {
return FilterConstants.PRE_TYPE;
}
@Override
public int filterOrder() {
return FilterConstants.PRE_DECORATION_FILTER_ORDER + 1; //PreDecorationFilter会对服务做封装,故在它之后修改
}
@Override
public boolean shouldFilter() {
return true;
}
@Data
public static class ServiceDto {
@JsonProperty("service_code")
private String serviceCode;
}
}
版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/03/26/implement-zuul-dynamic-routing-through-configuration-method/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。
THE END
0
二维码
打赏
海报
配置方式实现Zuul动态路由
Zuul路由信息可以来自Properties文件、DB、Apollo等。
zuul:
host:
connect-timeout-millis: 3000
socket-timeout-millis: 20000
routes:
uni……
文章目录
关闭
共有 0 条评论