ribbon个性化参数设置

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

RibbonRequestCustomizer

package org.springframework.cloud.netflix.ribbon.support;

import java.util.List;

/**
 * @author Spencer Gibb
 */
public interface RibbonRequestCustomizer {
    boolean accepts(Class builderClass);
    void customize(B builder);

    class Runner {

        @SuppressWarnings("unchecked")
        public static void customize(List 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 apacheHttpRibbonRequestCustomizer() {
        return new ApacheHttpClientRibbonRequestCustomizer();
    }

ApacheHttpClientRibbonRequestCustomizer

public class ApacheHttpClientRibbonRequestCustomizer implements RibbonRequestCustomizer {
    @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个性化参数设置)