Ribbon integration Consul, No instances available for XXX abnormal

First posted Code:

@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 Residual Template rest template () {
         return  new Rest Template (); 
    }
    @Autowired 
    IClientConfig config; 
    
    / ** 
     * Set the load balancing rules for random 
     * * / 
    @Bean 
    public IRule MyRibbonRule () { 
        System.out.println ( "random ...." );
         return  new 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

Indeed, / call request mapping method has problems;

The problem is here because LoadBalancedClient choose according to Consul registered service name ( spring.cloud.consul.discovery.serviceName = Service-Producer hit a service provider);

Here you can not use the object LoadBalanced added RestTemplate annotation, because looks for a service provider to host according to Consul, this will throw an exception: No instances available for XXX, also could not find the specified service ID

Solution:

Reason: LoadBalancerClient manual http request; the Ribbon integrated Apache HttpClient, OkHttp use the requesting client;
ribbon.okhttp.enabled= true
ribbon.restclient.enabled= true

 

Reference link: https: //www.cnblogs.com/XingXiaoMeng/p/10958644.html

 

Guess you like

Origin www.cnblogs.com/muxi0407/p/11655697.html