在没有Spring Cloud的情况下使用RibbonClient和Consul发现
作者:互联网
我试图设置Feign来使用RibbonClient,比如MyService api = Feign.builder().client(RibbonClient.create()).target(MyService.class,“https:// myAppProd”);,其中myAppProd是我可以在领事中看到的应用程序.现在,如果我为Feign客户端使用Spring注释(@FeignClient(“myAppProd”),@ RequestMapping),一切都可行,因为Spring Cloud模块将处理所有事情.
如果我想使用Feign.builder()和@RequestLine,我会收到错误:
com.netflix.client.ClientException:负载均衡器没有客户端的可用服务器:myAppProd.
我的第一个初步想法是,Feign是为与Eureka合作而建立的,只有Spring Cloud与Consul集成,但我不确定这一点.
那么,有没有办法让Feign在没有Spring Cloud的情况下与Consul合作?
提前致谢.
解决方法:
在我看来,这不是与领事的假装工作,它的假装 – >功能区 – >领事.
RibbonClient需要从其LoadBalancer中找到myAppProd的serverList.
没有ServerList,错误:’没有可用的客户端服务器’.
这项工作已由SpringCloudConsul和SpringCloudRibbon项目完成,当然你可以编写另一个适配器,它只是一些粘合代码.恕我直言,你可以将这个spring依赖项导入到你的项目中,但是以非spring方式使用它.演示代码:
只需编写一个新的feign.ribbon.LBClientFactory,用ConsulServerList(Spring的类)生成LBClient.
public class ConsulLBFactory implements LBClientFactory {
private ConsulClient client;
private ConsulDiscoveryProperties properties;
public ConsulLBFactory(ConsulClient client, ConsulDiscoveryProperties consulDiscoveryProperties) {
this.client = client;
this.properties = consulDiscoveryProperties;
}
@Override
public LBClient create(String clientName) {
IClientConfig config =
ClientFactory.getNamedConfig(clientName, DisableAutoRetriesByDefaultClientConfig.class);
ConsulServerList consulServerList = new ConsulServerList(this.client, properties);
consulServerList.initWithNiwsConfig(config);
ZoneAwareLoadBalancer<ConsulServer> lb = new ZoneAwareLoadBalancer<>(config);
lb.setServersList(consulServerList.getInitialListOfServers());
lb.setServerListImpl(consulServerList);
return LBClient.create(lb, config);
}
}
然后在假装中使用它:
public class Demo {
public static void main(String[] args) {
ConsulLBFactory consulLBFactory = new ConsulLBFactory(
new ConsulClient(),
new ConsulDiscoveryProperties(new InetUtils(new InetUtilsProperties()))
);
RibbonClient ribbonClient = RibbonClient.builder()
.lbClientFactory(consulLBFactory)
.build();
GitHub github = Feign.builder()
.client(ribbonClient)
.decoder(new GsonDecoder())
.target(GitHub.class, "https://api.github.com");
List<Contributor> contributors = github.contributors("OpenFeign", "feign");
for (Contributor contributor : contributors) {
System.out.println(contributor.login + " (" + contributor.contributions + ")");
}
}
interface GitHub {
@RequestLine("GET /repos/{owner}/{repo}/contributors")
List<Contributor> contributors(@Param("owner") String owner, @Param("repo") String repo);
}
public static class Contributor {
String login;
int contributions;
}
}
你可以找到这个demo code here,在运行这个演示之前将api.github.com添加到你当地的领事馆.
标签:spring,spring-cloud-feign,consul,netflix-feign,netflix-ribbon 来源: https://codeday.me/bug/20190710/1428169.html