@Configuration
public class BeanConfig {
@LoadBalanced
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
@Autowired
RestTemplate restTemplate;
// @Resource
// private LoadBalancerClient loadBalancerClient;
@RequestMapping("/order-hello")
public Object orderHello(){
// ServiceInstance serviceInstance = loadBalancerClient.choose("logistics");
// return serviceInstance==null?"null":serviceInstance.getHost()+serviceInstance.getPort();
return restTemplate.getForObject("http://order"+"/api/hello",String.class);
// return null;
// return restTemplate.getForObject("http://127.0.0.1:8080"+"/api/hello",String.class);
}
报错如下
023-02-23T11:11:17.153+08:00 INFO 22144 --- [nio-7070-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2023-02-23T11:11:17.154+08:00 INFO 22144 --- [nio-7070-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
2023-02-23T11:11:19.457+08:00 ERROR 22144 --- [nio-7070-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://order/api/hello": order] with root cause
java.net.UnknownHostException: order
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:567) ~[na:na]
at java.base/java.net.Socket.connect(Socket.java:633) ~[na:na]
at java.base/java.net.Socket.connect(Socket.java:583) ~[na:na]
发现问题了
springcloud 莫个版本后不支持ribbon 了,需要导入下面这个包,而且要是正确的版本。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
<version>4.0.1</version>
</dependency>
标签:return,na,restTemplate,nacos,java,order,ribbon,serviceInstance
From: https://www.cnblogs.com/come-here/p/17147327.html