记录一个这个bug
我发生这个bug的场景是在使用Eureka注册服务之后,通过返回RestTemplate对象,但在使用对象时的getForObject方法的过程中,url中写的是localhost+端口号。
import org.springframework.web.client.RestClientException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@RestController
public class UserController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/findOrderByUser/{id}")
public ResponseEntity<String> findOrderByUser(@PathVariable String id) {
try {
String result = this.restTemplate.getForObject("http://localhost:7900/order/" + id, String.class);
return ResponseEntity.ok(result);
} catch (RestClientException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error fetching order data");
}
}
}
这本来是没有任何问题的。
关键点在于使用Ribbon负载均衡后,也就是加上@LoadBalanced注解后
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
使用上述方法返回数据,报上述错误。
其实是在没有使用 @LoadBalanced 注解之前,代码直接使用 localhost:7900 作为请求的目的地,这是一个硬编码的地址。当添加了 @LoadBalanced 注解之后,Spring Cloud 会尝试使用服务发现(例如Eureka)来解析服务名称,并执行客户端负载均衡。
这时候Spring Cloud 无法从服务发现组件找到名为 localhost 的服务实例。
于是报java.lang.IllegalStateException: No instances available for localhost
去访问Eureka注册信息页面,查看你的实例名称,然后用实例名称代替你的(ip+端口号)
@GetMapping("/findOrderByUser/{id}")
public String findOrderByUser(@PathVariable String id) {
String url = "http://MICROSERVICE-EUREKA-ORDER/order/" + id;
return this.restTemplate.getForObject(url, String.class);
}
例如:用MICROSERVICE-EUREKA-ORDER替换localhost:7900
1万+

被折叠的 条评论
为什么被折叠?



