美文网首页springcloud
ribbon个性化参数设置

ribbon个性化参数设置

作者: go4it | 来源:发表于2017-06-28 23:50 被阅读32次

    当使用zuul作为api网关的时候,默认的ribbon的超时设置是针对整个service的,那么如果想针对某几个url单独设置超时,该怎么办呢?

    RibbonRequestCustomizer

    package org.springframework.cloud.netflix.ribbon.support;
    
    import java.util.List;
    
    /**
     * @author Spencer Gibb
     */
    public interface RibbonRequestCustomizer<B> {
        boolean accepts(Class builderClass);
        void customize(B builder);
    
        class Runner {
    
            @SuppressWarnings("unchecked")
            public static void customize(List<RibbonRequestCustomizer> customizers, Object builder) {
                for (RibbonRequestCustomizer customizer : customizers) {
                    if (customizer.accepts(builder.getClass())) {
                        customizer.customize(builder);
                    }
                }
            }
        }
    }
    

    使用

    @Bean
        @ConditionalOnClass(name = "org.apache.http.client.methods.RequestBuilder")
        public RibbonRequestCustomizer<RequestBuilder> apacheHttpRibbonRequestCustomizer() {
            return new ApacheHttpClientRibbonRequestCustomizer();
        }
    

    ApacheHttpClientRibbonRequestCustomizer

    public class ApacheHttpClientRibbonRequestCustomizer implements RibbonRequestCustomizer<RequestBuilder> {
        @Override
        public boolean accepts(Class builderClass) {
            return builderClass.equals(RequestBuilder.class);
        }
    
        @Override
        public void customize(RequestBuilder builder) {
            URI uri = builder.getUri();
            String path = uri.getPath(); //"/review/timeout"
            System.out.println("request customizer uri:"+path);
            RequestConfig.Builder configBuilder = builder.getConfig() == null ? RequestConfig.custom():RequestConfig.copy(builder.getConfig());
    
            if(path.equals("/review/timeout")){
                configBuilder.setConnectionRequestTimeout(30*1000);
                configBuilder.setConnectTimeout(30*1000);
                configBuilder.setSocketTimeout(30*1000);
                builder.setConfig(configBuilder.build());
            }
            //todo 这里设置没有用,最后还是会被重置
            //org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpRequest.java 76
            //read config
    
        }
    }
    

    结论

    这种方式目前还不能个性化timeout参数,因为最后在RibbonApacheHttpRequest会被重置回来,但是可以添加一些header之类的。

    相关文章

      网友评论

        本文标题:ribbon个性化参数设置

        本文链接:https://www.haomeiwen.com/subject/qovpcxtx.html