序
当使用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之类的。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。