No instances available for XXX

伟衙内發表於2024-10-07

 spring cloud 使用nacos作為服務發現,ribbon做負載均衡,然後報錯,No instances available for cloud-alibaba-study。

版本

  Spring boot 2.6.7

  Spring cloud 2021.0.3

  Spring cloud alibaba 2021.0.6.0

過程

  當我引入nacos包如下,2021.0.6.0包移除了ribbon,(除非使用2.2.7.RELEASE版本,參考https://blog.csdn.net/qq_30946821/article/details/117433812

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

  所以我手動加入了ribbon包,

<!-- Ribbon 依賴 -->
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-ribbon -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
    <version>2.2.7.RELEASE</version>
</dependency>

  接下來報錯,

Description:

Parameter 0 of method loadBalancerWebClientBuilderBeanPostProcessor in org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerBeanPostProcessorAutoConfiguration required a bean of type 'org.springframework.cloud.client.loadbalancer.reactive.DeferringLoadBalancerExchangeFilterFunction' that could not be found.

Action:

Consider defining a bean of type 'org.springframework.cloud.client.loadbalancer.reactive.DeferringLoadBalancerExchangeFilterFunction' in your configuration.

  然後我加入了spring-cloud-starter-loadbalancer包,

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>

  結果報錯No instances available for cloud-alibaba-study。

  服務列表也有,如下圖

No instances available for XXX

  查了文件才知道

  從 Spring Cloud 2020.0.0 版本開始,Spring Cloud 官方推薦使用 spring-cloud-starter-loadbalancer 作為負載均衡器,而不是 Ribbon。你可以考慮使用 Spring Cloud LoadBalancer 替代 Ribbon。

  所以我在想是不是loadbalancer和ribbon包衝突,

  刪除 spring-cloud-starter-netflix-ribbon 包,正常。

  

呼叫方式如下,

@Bean
@LoadBalanced
public RestTemplate restTemplate(){
    return new RestTemplate();
}
@RequestMapping("/loadBalance")
public List<ServiceInstance> loadBalance(){
    return this.restTemplate.getForObject("http://cloud-alibaba-study/getInstances",List.class);
}

相關文章