{"record":{"id":"8ef9155dc9a92097","repo":"yudaocode/SpringBoot-Labs","slug":"error-8ef915","errorCode":null,"errorMessage":"获取不到实例","messagePattern":"获取不到实例","errorType":"exception","errorClass":"IllegalStateException","httpStatus":500,"severity":"error","filePath":"labx-22/labx-22-scn-eureka-demo02-consumer/src/main/java/cn/iocoder/springcloudalibaba/labx22/consumerdemo/DemoConsumerApplication.java","lineNumber":59,"sourceCode":"        private RestTemplate restTemplate;\n        @Autowired\n        private LoadBalancerClient loadBalancerClient;\n\n        @GetMapping(\"/hello\")\n        public String hello(String name) {\n            // 获得服务 `demo-provider` 的一个实例\n            ServiceInstance instance;\n            if (true) {\n                // 获取服务 `demo-provider` 对应的实例列表\n                List<ServiceInstance> instances = discoveryClient.getInstances(\"demo-provider\");\n                // 选择第一个\n                instance = instances.size() > 0 ? instances.get(0) : null;\n            } else {\n                instance = loadBalancerClient.choose(\"demo-provider\");\n            }\n            // 发起调用\n            if (instance == null) {\n                throw new IllegalStateException(\"获取不到实例\");\n            }\n            String targetUrl = instance.getUri() + \"/echo?name=\" + name;\n            String response = restTemplate.getForObject(targetUrl, String.class);\n            // 返回结果\n            return \"consumer:\" + response;\n        }\n\n    }\n\n}\n","sourceCodeStart":41,"sourceCodeEnd":70,"githubUrl":"https://github.com/yudaocode/SpringBoot-Labs/blob/6c12efaed06d12907a0f40dd2ad1f7020aec8798/labx-22/labx-22-scn-eureka-demo02-consumer/src/main/java/cn/iocoder/springcloudalibaba/labx22/consumerdemo/DemoConsumerApplication.java#L41-L70","documentation":"Same guard as the demo01 consumer, in the labx-22 demo02 variant (Eureka): DemoConsumerApplication fetches DiscoveryClient.getInstances(\"demo-provider\"), takes instances.get(0) only when the list is non-empty, and otherwise throws IllegalStateException(\"获取不到实例\") at line 59. The registry query returned zero instances for the service name 'demo-provider'. In the demo02 lab the provider module is the demo02 provider — the consumer code still hard-codes the logical name 'demo-provider', so a name/config mismatch between the demo02 provider's spring.application.name and this literal is a frequent cause unique to this variant.","triggerScenarios":"Calling the consumer endpoint while getInstances(\"demo-provider\") is empty: provider (demo02) not started, registered under a different spring.application.name, registration still propagating, Eureka server unreachable from either side, or the instance evicted (lease expiry / health-check failure).","commonSituations":"Provider started but with a name other than 'demo-provider'; consumer pointed at a different Eureka server than the provider (mismatched eureka.client.serviceUrl.defaultZone); consumer started immediately after the provider so the local fetch cache has not refreshed yet; provider crashed after registration and Eureka evicted it; copy-pasting this consumer against a provider from another lab module.","solutions":["Open the Eureka dashboard and confirm a service named exactly 'demo-provider' (the name passed to getInstances) is UP; fix the provider's spring.application.name if it differs.","Reorder startup: Eureka server → demo02 provider → wait for UP status → consumer; then retry the request.","Align eureka.client.serviceUrl.defaultZone between provider and consumer so both talk to the same registry.","Handle the empty case gracefully (503 + message) or use LoadBalancerClient.choose with a null check when absence is expected."],"exampleFix":"// before\ninstance = instances.size() > 0 ? instances.get(0) : null;\nif (instance == null) {\n    throw new IllegalStateException(\"获取不到实例\");\n}\n\n// after\nif (instances.isEmpty()) {\n    return \"service demo-provider unavailable, please retry later\";\n}\nServiceInstance instance = instances.get(0);","handlingStrategy":"validation","validationCode":"List<ServiceInstance> instances = discoveryClient.getInstances(\"demo-provider\");\nif (instances.isEmpty()) {\n    return \"demo-provider 暂无可用实例，请确认提供者已注册并稍后重试\";\n}\nServiceInstance instance = instances.get(0);","typeGuard":"Optional<ServiceInstance> firstInstance(DiscoveryClient dc, String service) {\n    List<ServiceInstance> list = dc.getInstances(service);\n    return (list == null || list.isEmpty()) ? Optional.empty() : Optional.of(list.get(0));\n}","tryCatchPattern":"try {\n    return \"consumer:\" + restTemplate.getForObject(targetUrl, String.class);\n} catch (RestClientException e) {\n    // instance disappeared between discovery and call: refresh and retry once\n    List<ServiceInstance> retry = discoveryClient.getInstances(\"demo-provider\");\n    if (retry.isEmpty()) throw new IllegalStateException(\"获取不到实例\");\n    return \"consumer:\" + restTemplate.getForObject(retry.get(0).getUri() + \"/echo?name=\" + name, String.class);\n}","preventionTips":["Verify the exact service name on the Eureka dashboard matches the getInstances literal before wiring consumers.","Use shared configuration for eureka.client.serviceUrl.defaultZone so provider and consumer cannot diverge.","Sequence demo startups (registry, provider, consumer) and wait for UP status; add retry/backoff for the registration window.","Return 503 with guidance on empty discovery instead of letting IllegalStateException surface as a 500."],"tags":["eureka","service-discovery","spring-cloud","registration","labx-22"],"backgroundTag":null,"analyzedSha":"6c12efaed06d12907a0f40dd2ad1f7020aec8798","analyzedAt":"2026-08-14T13:06:31.500Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}