我有一个Spring Cloud应用程序,我正在自定义功能区客户端,如" 自定义功能区客户端"一节中所述,我的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或Feign,或者如果您有另一个使用Ribbon的选项...)
编辑可能的方向
在AbstractLoadBalancerAwareClient类中
public T executeWithLoadBalancer(final S request, final IClientConfig requestConfig) throws ClientException { RequestSpecificRetryHandler handler = getRequestSpecificRetryHandler(request, requestConfig); LoadBalancerCommandcommand = LoadBalancerCommand. 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";
似乎应该使用此名称进行一些配置,因为我看到我的loadbalancer服务器列表由于某种原因总是空的,如果有人知道我应该如何配置此属性我相信它可以解决问题...