yudaocode/SpringBoot-Labs · error · IllegalStateException

获取不到实例

Error message

获取不到实例

What it means

Identical pattern in the labx-22 demo03 consumer: it queries Eureka for 'demo-provider' via DiscoveryClient, selects the first instance, and throws IllegalStateException("获取不到实例") at DemoConsumerApplication.java:59 when none exist. Zero registered-and-UP instances for the requested name at the moment of the call. demo03 in this lab typically demonstrates Feign or registry-detail variations, but this controller path uses raw DiscoveryClient, so the failure mode is the registry contents, not the Feign layer.

Source

Thrown at labx-22/labx-22-scn-eureka-demo03-consumer/src/main/java/cn/iocoder/springcloudalibaba/labx22/consumerdemo/DemoConsumerApplication.java:59

        private RestTemplate restTemplate;
        @Autowired
        private LoadBalancerClient loadBalancerClient;

        @GetMapping("/hello")
        public String hello(String name) {
            // 获得服务 `demo-provider` 的一个实例
            ServiceInstance instance;
            if (true) {
                // 获取服务 `demo-provider` 对应的实例列表
                List<ServiceInstance> instances = discoveryClient.getInstances("demo-provider");
                // 选择第一个
                instance = instances.size() > 0 ? instances.get(0) : null;
            } else {
                instance = loadBalancerClient.choose("demo-provider");
            }
            // 发起调用
            if (instance == null) {
                throw new IllegalStateException("获取不到实例");
            }
            String targetUrl = instance.getUri() + "/echo?name=" + name;
            String response = restTemplate.getForObject(targetUrl, String.class);
            // 返回结果
            return "consumer:" + response;
        }

    }

}

View on GitHub (pinned to 6c12efaed0)

Solutions

  1. Verify on the Eureka dashboard that 'demo-provider' is registered and UP; start the demo03 provider if it is not.
  2. Fix name mismatch: provider's spring.application.name must equal the getInstances argument exactly.
  3. Give registration time (start provider, wait for UP, then call) — first calls right after startup commonly fail.
  4. Check eureka.client.serviceUrl.defaultZone in both apps and eureka.client.fetch-registry=true in the consumer.
  5. Replace the bare throw with explicit empty-list handling or a load-balanced RestTemplate if you want automatic retry across instances.

Example fix

// before
instance = instances.size() > 0 ? instances.get(0) : null;
if (instance == null) {
    throw new IllegalStateException("获取不到实例");
}

// after
if (instances.isEmpty()) {
    throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE,
        "demo-provider has no instances; check Eureka registration");
}
ServiceInstance instance = instances.get(0);
Defensive patterns

Strategy: validation

Validate before calling

if (!discoveryClient.getInstances("demo-provider").isEmpty()) {
    ServiceInstance instance = discoveryClient.getInstances("demo-provider").get(0);
    // proceed with the call
} else {
    throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "demo-provider 暂无可用实例");
}

Type guard

boolean providerAvailable(DiscoveryClient dc) {
    List<ServiceInstance> list = dc.getInstances("demo-provider");
    return list != null && !list.isEmpty() && list.get(0).getUri() != null;
}

Try / catch

catch (IllegalStateException e) {
    if ("获取不到实例".equals(e.getMessage())) {
        // empty registry result: report degraded dependency, schedule retry
        return ResponseEntity.status(503).body("demo-provider not registered yet");
    }
    throw e;
}

Prevention

When it happens

Trigger: /echo request while getInstances("demo-provider") returns []: demo03 provider not running, wrong/missing spring.application.name, Eureka server down or wrong zone URL in either app, registration/lease-propagation delay, or the instance evicted after heartbeat loss.

Common situations: Running only the consumer module of the multi-module lab; renaming services between demo01/02/03 modules while the consumer literal stays 'demo-provider'; local Eureka not started (check the server process/port, default 8761); firewall/port conflict preventing the provider's registration; consumer's eureka.client.enabled or fetch-registry settings disabled in its yaml.

Related errors


AI-assisted analysis of yudaocode/SpringBoot-Labs@6c12efaed0 (2026-08-14). Data as JSON: /api/errors/e409d12e429297ea. Report an issue: GitHub.