ribbon個性化參數設置

當使用zuul做爲api網關的時候,默認的ribbon的超時設置是針對整個service的,那麼若是想針對某幾個url單獨設置超時,該怎麼辦呢?java

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之類的。spring

相關文章
相關標籤/搜索