关于Springcloud的RestTemplate使用服务名报异常java.net.UnknownHostException和使用localhost:8081报异常java.lang.IllegalStateException: No instances available for localhost问题
1.关于java.lang.IllegalStateException: No instances available for localhost问题
在Springcloud使用RestTemplate访问其他模块的时候,可能会出现java.lang.IllegalStateException: No instances available for localhost问题。也有时候回出现空指针的问题。对于这类Bug解决的方法可能是由于你的restTemplate配置的问题。这些问题发生在访问的模块,被访问的模块这里就不用写出来了。
首先是启动类和restTemplate配置。这里需要注意的是,如果restTemplate对象是用纯地址访问的话,就不需要@LoadBalanced这个标签,如果
@SpringBootApplication
@EnableEurekaClient
public class RibbonApplication {
@Bean
//@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(RibbonApplication.class,args);
}
}
然后就是controller层通过restTemplate对象访问其他模块接口的方法
@RestController
public class UserController {
@Autowired
private RestTemplate restTemplate;
/***
* 通过ribbon和template对象访问 user里面的数据
*/
@GetMapping("/movie/{id}")
public User findById(@PathVariable Long id) {
System.err.println("consumer---------------------"+id);
return this.restTemplate.getForObject("http://localhost:7900/simple/"+ id, User.class);
}
}
值得注意的是,如果你不注释 //@LoadBalanced这个标签的话,就会报出一下错误:java.lang.IllegalStateException: No instances available for localhost。所以解决这种异常的方法是注释掉@LoadBalanced这个标签
2.关于Springcloud的RestTemplate不能使用服务名java.net.UnknownHostException: micorservice-provider-user
如果restTemplate对象需要使用服务名的话会报异常:java.net.UnknownHostException: micorservice-provider-user。 micorservice-provider-user是其他模块的服务名
服务名:
启动类代码
@SpringBootApplication
@EnableEurekaClient
public class RibbonApplication {
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(RibbonApplication.class,args);
}
}
访问其他模块的接口的代码
@RestController
public class UserController {
@Autowired
private RestTemplate restTemplate;
/***
* 通过ribbon和template对象访问 user里面的数据
*/
@GetMapping("/movie/{id}")
public User findById(@PathVariable Long id) {
System.err.println("consumer---------------------"+id);
//这里使用的micorservice-provider-user是其他模块的服务名
return this.restTemplate.getForObject("http://micorservice-provider-user/simple/"+ id, User.class);
}
}
解决这类异常的方法是在resttemplate配置 @LoadBalanced这个注解
3.总结
如果需要使用ip和端口,就不需要加 @LoadBalanced注解,如果需要使用应用名访问,那就需要在restTemplate配置加上 @LoadBalanced注解 。因为@LoadBalanced这个注解是负载均衡的注解,而负载均衡就是通过访问服务名而实现的。如果你加上这个注解之后使用restTemplate,那么他就默认你的localhost一个模块的服务名称(ip+端口),而不是本机的ip。总而言之,如果需要使用ip和端口,就不需要加 @LoadBalanced注解,如果需要使用应用名访问,那就需要在restTemplate配置加上 @LoadBalanced注解