{"id":1739,"date":"2023-03-26T21:13:31","date_gmt":"2023-03-26T13:13:31","guid":{"rendered":"https:\/\/www.appblog.cn\/?p=1739"},"modified":"2023-04-23T21:30:27","modified_gmt":"2023-04-23T13:30:27","slug":"implement-zuul-dynamic-routing-through-configuration-method","status":"publish","type":"post","link":"https:\/\/www.appblog.cn\/index.php\/2023\/03\/26\/implement-zuul-dynamic-routing-through-configuration-method\/","title":{"rendered":"\u914d\u7f6e\u65b9\u5f0f\u5b9e\u73b0Zuul\u52a8\u6001\u8def\u7531"},"content":{"rendered":"<p>Zuul\u8def\u7531\u4fe1\u606f\u53ef\u4ee5\u6765\u81eaProperties\u6587\u4ef6\u3001DB\u3001Apollo\u7b49\u3002<\/p>\n<pre><code class=\"language-yml\">zuul:\n  host:\n    connect-timeout-millis: 3000\n    socket-timeout-millis: 20000\n  routes:\n    unified:\n      path: \/gw\/**\n      serviceId: gw\n      sensitiveHeaders:\nroutes:\n  services:\n    union_pay_online: ok-cloud-union-pay-online\n    union_pay_offline: ok-cloud-union-pay-offline<\/code><\/pre>\n<p><!-- more --><\/p>\n<pre><code class=\"language-java\">@Data\n@Configuration\n@ConfigurationProperties(prefix = &quot;routes&quot;)\npublic class RouteConfig {\n    @NestedConfigurationProperty\n    private Map&lt;String, String&gt; services = new HashMap&lt;&gt;();\n}<\/code><\/pre>\n<pre><code class=\"language-java\">@Slf4j\n@Component\npublic class RouteFilter extends ZuulFilter {\n    @Autowired\n    RouteConfig routeConfig;\n\n    @Override\n    public Object run() throws ZuulException {\n        RequestContext ctx = RequestContext.getCurrentContext();\n        if (!ctx.sendZuulResponse()) {\n            return null;\n        }\n        HttpServletRequest request = ctx.getRequest();\n        log.info(&quot;\u8bf7\u6c42uri: {}&quot;, request.getRequestURI());\n        Object originalRequestPath = ctx.get(FilterConstants.REQUEST_URI_KEY);\n        log.info(&quot;originalRequestPath = {}&quot;, originalRequestPath);\n        try {\n            String serviceCode = request.getParameter(&quot;service_code&quot;);\n            if (isBlank(serviceCode)) {\n                String requestBody = StreamUtils.copyToString(request.getInputStream(), Charset.forName(CharEncoding.UTF_8));\n                ServiceDto dto = JSON.parseObject(requestBody, ServiceDto.class);\n                serviceCode = dto.getProduct_code();\n            }\n            if (isBlank(serviceCode)) {\n                sendErrorResponse(ResultBuilder.failure(ResponseCode.BAD_REQUEST.code(), &quot;service_code is blank&quot;));\n                return null;\n            }\n            String serviceId = routeConfig.getServices().get(serviceCode.toLowerCase());\n            ctx.put(FilterConstants.SERVICE_ID_KEY, serviceId);\n            ctx.put(FilterConstants.PROXY_KEY, serviceId);\n            \/\/ctx.put(REQUEST_URI_KEY, route.getPath());\n        } catch (Exception e) {\n            log.error(&quot;&quot;, e);\n            sendErrorResponse(ResultBuilder.failure(ResponseCode.SERVICE_UNAVAILABLE));\n        }\n        return null;\n    }\n\n    private void sendErrorResponse(Result result) {\n        RequestContext requestContext = RequestContext.getCurrentContext();\n        requestContext.setSendZuulResponse(false);\n        requestContext.addZuulResponseHeader(&quot;Content-type&quot;, &quot;application\/json;charset=UTF-8&quot;);\n        requestContext.setResponseBody(JSON.toJSONString(result));\n    }\n\n    @Override\n    public String filterType() {\n        return FilterConstants.PRE_TYPE;\n    }\n\n    @Override\n    public int filterOrder() {\n        return FilterConstants.PRE_DECORATION_FILTER_ORDER + 1;  \/\/PreDecorationFilter\u4f1a\u5bf9\u670d\u52a1\u505a\u5c01\u88c5\uff0c\u6545\u5728\u5b83\u4e4b\u540e\u4fee\u6539\n    }\n\n    @Override\n    public boolean shouldFilter() {\n        return true;\n    }\n\n    @Data\n    public static class ServiceDto {\n        @JsonProperty(&quot;service_code&quot;)\n        private String serviceCode;\n    }\n}<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Zuul\u8def\u7531\u4fe1\u606f\u53ef\u4ee5\u6765\u81eaProperties\u6587\u4ef6\u3001DB\u3001Apollo\u7b49\u3002 zuul: host: connec [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[42],"tags":[250],"class_list":["post-1739","post","type-post","status-publish","format-standard","hentry","category-spring-cloud","tag-zuul"],"_links":{"self":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/posts\/1739","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/comments?post=1739"}],"version-history":[{"count":0,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/posts\/1739\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/media?parent=1739"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/categories?post=1739"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/tags?post=1739"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}