配置方式实现Zuul动态路由

Zuul路由信息可以来自Properties文件、DB、Apollo等。

1
2
3
4
5
6
7
8
9
10
11
12
13
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
1
2
3
4
5
6
7
@Data
@Configuration
@ConfigurationProperties(prefix = "routes")
public class RouteConfig {
@NestedConfigurationProperty
private Map<String, String> services = new HashMap<>();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
@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;
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2021 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :