我有一个Spring应用程序,我正在自定义色带客户端,正如解释的这里是自定义丝带客户端的部分。,我的IRule如下所示:
public class HeadersRule extends AbstractLoadBalancerRule {
public HeadersRule () {
}
public HeadersRule(ILoadBalancer lb) {
this();
this.setLoadBalancer(lb);
}
public Server choose(ILoadBalancer lb, Object key) {
//I want the key to contain the headers from the request so I can decide choose the server by one of the headers
}我有一个休息控制器:
@RequestMapping("/")
public String hello(HttpServletRequest request, HttpServletResponse response) {
//here I want to pass the key parameter to ribbon
return result;
}我希望在我的IRule中通过一个标头的值来选择下一个服务器。如何将标题传递给我的自定义IRule键参数?(通过RestTemplate或假装,或者如果您有另一个选项使用丝带.)
编辑可能的方向
在类中AbstractLoadBalancerAwareClient
public T executeWithLoadBalancer(final S request, final IClientConfig requestConfig) throws ClientException {
RequestSpecificRetryHandler handler = getRequestSpecificRetryHandler(request, requestConfig);
LoadBalancerCommand<T> command = LoadBalancerCommand.<T>builder()
.withLoadBalancerContext(this)
.withRetryHandler(handler)
.withLoadBalancerURI(request.getUri())
.build();构建LoadBalancer命令并省略:
.withServerLocator(request)就能完成任务了!我可以从配置中重写此方法,在Spring RibbonClientConfiguration类中,我可以配置:
@Bean
@Lazy
@ConditionalOnMissingBean
public RestClient ribbonRestClient(IClientConfig config, ILoadBalancer loadBalancer) {
RestClient client = new OverrideRestClient(config);
client.setLoadBalancer(loadBalancer);
Monitors.registerObject("Client_" + this.name, client);
return client;
}问题是有这个名字的东西不起作用:
@Value("${ribbon.client.name}")
private String name = "client";似乎有一些配置应该用这个名称来完成,因为我看到我的负载平衡器服务器列表由于某种原因总是空的,如果有人知道我应该如何配置这个属性,我相信它可以解决这个问题……
发布于 2016-01-05 06:46:04
我采用了您的方法,并对其进行了一些修改:除了使用ribbonRestClient bean之外,还需要提供ribbonServerList bean。但是不要使用在RibbonClientConfiguration中定义的bean,它使用ConfigurationBasedServerList。所以你才会得到一张空名单。您可以定义服务器列表您的配置,或者,如果您喜欢使用eureka,可以从EurekaRibbonClientConfiguration获取bean:
@Bean
@ConditionalOnMissingBean
public ServerList<?> ribbonServerList(IClientConfig config) {
DiscoveryEnabledNIWSServerList discoveryServerList = new DiscoveryEnabledNIWSServerList(
config);
DomainExtractingServerList serverList = new DomainExtractingServerList(
discoveryServerList, config, this.approximateZoneFromHostname);
return serverList;
}它将动态填充服务器列表。此外,确保用于覆盖ribbonRestClientBean的配置文件不是自动扫描的。这就是导致
@Value("${ribbon.client.name}")
private String name = "client";若要在加载应用程序时尝试并填充,请执行以下操作。要么将配置放在主app类的不同包中,要么将其排除在扫描之外。
最后,不要忘记将@RibbonClient / @RibbonClients添加到主类以指向覆盖的配置。
@RibbonClients(defaultConfiguration = {my.non.autoScanned.MyRibbonClientConfiguration.class} )
@SpringBootApplication()
public class MyApp {https://stackoverflow.com/questions/34456075
复制相似问题