java.lang.IllegalStateException: No instances available for localhost

记录一个这个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

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

And涛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值