SpringCloud 消费请求Eureka调用服务提供者报错
SpringCloud 消费请求Eureka调用服务提供者报错
springCloud 2022.0.1
springboot 3.0.2
消费程序 通过eureka集群查询服务,根据eureka中注册的服务名称请求最终的服务,
//eureka 注册的服务名称,
public static final String PAYMENT_URL="http://PAYMENT-SERVICE";
@Resource
private RestTemplate restTemplate;
@RequestMapping("/consumer/payment/get/{id}") public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) { return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id ,CommonResult.class); }
报错:
java.net.UnknownHostException: PAYMENT-SERVICE
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:560)
at java.base/java.net.Socket.connect(Socket.java:666)
at java.base/java.net.Socket.connect(Socket.java:600)
at java.base/sun.net.NetworkClient.doConnect(NetworkClient.java:183)
at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:531)
在restTemplate bean上增加注解 @LoadBanlanced
@Configuration public class AppContextConfig { @Bean @LoadBalanced public RestTemplate getRestTmp() { return new RestTemplate(); } }
原因:
服务有多个, 如果不开启负载均衡,eureka不知道是分配哪一个 ,会报这个错误 ERROR:java.net.UnknownHostException: