解决java.lang.IllegalStateException: No instances available for service-provider] with root cause java问题

前提是服务已经在Consul注册成功了,但是service-provider服务健康检查未通过

浏览器访问订单页面

在这里插入图片描述

后台报错

在这里插入图片描述

检查Consul服务出现健康检查没有通过

在这里插入图片描述

问题分析

1.出现Consul监控检查未通过,可以从以下几个方面进行检查:

1)检查pom文件中是否添加如下依赖:

 <!--spring boot actuator依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

2)检查application.yaml文件中,application与cloud是否对齐(我的是因为没有对齐才出现健康检查未通过)

server:
  port: 7070 # 端口
spring:
  application:
    name: service-provider # 应用名称
    # 配置Consul注册中心
  cloud:
    consul:
      # 注册中心的访问地址
      host: localhost
      port: 8500
      # 服务提供者信息
      discovery:
        register: true # 是否需要注册
        instance-id: ${spring.application.name}-01 # 注册实例id(必须唯一)
        service-name: ${spring.application.name} # 服务名称
        port: ${server.port} # 服务端口
        prefer-ip-address: true #是否使用ip地址注册
        ip-address: ${spring.cloud.client.ip-address} # 服务请求ip

2.出现java.lang.IllegalStateException: No instances available for service-provider] with root cause java,需要检查以下几个方面:

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 根据主键查询订单
     * @param id
     * @return
     */
    @Override
    public Order selectOrderById(Integer id) {
        return new Order(id,"order-001","中国",22780D,selectProductListByLoadBalancerAnnotation());
    }

    private List<Product> selectProductListByLoadBalancerAnnotation() {
        //ResponseEntity:封装了返回数据
        ResponseEntity<List<Product>> response = restTemplate.exchange("http://service-provider/product/list",
                HttpMethod.GET, null, new ParameterizedTypeReference<List<Product>>() {
                });
        return response.getBody();
    }
}
@SpringBootApplication
public class ServiceConsumerApplication {
    /**
     * 注入restTemplate,使得restTemplate具有负载均衡的能力
     * @return
     */
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
    public static void main(String[] args) {
        SpringApplication.run(ServiceConsumerApplication.class, args);
    }
}

注意:
由于在启动类中引入了注解@LoadBalanced,所以OrderServiceImpl 类中exchange方法中的url必须采用的是http://应用名/product/list,其中应用名指的是application.yml文件中的
spring:
application:
name: service-provider # 应用名称

如果上述都检查没有问题,应该就不会出现java.lang.IllegalStateException: No instances available for service-provider] with root cause java这个错误了

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐