当使用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之类的。


codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...