Ribbon personalization parameter settings

  springcloud

Order

When zuul is used as an api gateway, the default ribbon timeout is set for the entire service. what should I do if I want to set a timeout for a few URLs?

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);
                }
            }
        }
    }
}

Use

@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

    }
}

Conclusion

This method cannot personalize the timeout parameter at present, because the RibbonApacheHttpRequest will be reset back at last, but some header and the like can be added.