标签:hello 规则 strong auto random html blog logs 对象
先贴代码:
@RestController public class CallHelloController { @Autowired private LoadBalancerClient loadBalancerClient; @Autowired private RestTemplate restTemplate;
@RequestMapping("/call") public String call(){ ServiceInstance serviceInstance = loadBalancerClient.choose("service-producer"); System.out.println("服务地址:" + serviceInstance.getUri()); System.out.println("服务名称:" + serviceInstance.getServiceId()); String callServiceResult = restTemplate.getForObject(serviceInstance.getUri().toString() + "/hello", String.class); System.out.println(callServiceResult); return callServiceResult; }
@Bean @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); }
@Autowired IClientConfig config; /** * 设置负载均衡的规则为随机 * */ @Bean public IRule MyRibbonRule() { System.out.println("随机的...."); return new RandomRule(); //RandomRule RetryRule RoundRibinRule }
application.properties
spring.application.name=spring-cloud-consul-producer server.port=8802 spring.cloud.consul.host=localhost spring.cloud.consul.port=8500 #注册到consul的服务名称 spring.cloud.consul.discovery.serviceName=service-producer
实际上,/call请求映射方法存在问题;
问题是 因为 LoadBalancedClient 这里的 choose 根据 Consul注册的服务名(spring.cloud.consul.discovery.serviceName=service-producer) 命中一个服务提供者;
这里就不能使用加了LoadBalanced注解的RestTemplate对象了,因为会根据 host 去Consul查找服务提供者,这样就会抛异常 :No instances available for XXX ,也就是找不到指定的服务ID
解决办法:
原因:LoadBalancerClient进行手动的http请求;Ribbon集成了Apache HttpClient 、 OkHttp请求客户端使用;
ribbon.okhttp.enabled= true ribbon.restclient.enabled= true
参考链接:https://www.cnblogs.com/XingXiaoMeng/p/10958644.html
Ribbon整合Consul,出现No instances available for XXX 异常
标签:hello 规则 strong auto random html blog logs 对象
原文地址:https://www.cnblogs.com/muxi0407/p/11655697.html