# 简介
Spring提供的http请求,不推荐使用建议使用feign,或者从spring 6.1发布的 reactive WebClient
# 常见问题
# Service Instance cannot be null, serviceId: oapi.dingtalk.com at
Spring Cloud RestTemplate @LoadBalanced 支持ip、域名、服务名 调用
RestTemplate设置
@LoadBalanced
@Bean
public RestTemplate restTemplate(@Autowired ClientHttpRequestFactory clientHttpRequestFactory){
return new RestTemplate(clientHttpRequestFactory);
}
2
3
4
5
如果使用时通过域名或者ip:port调用,例如
restTemplate.getForObject("https://fanyi.baidu.com/#en/zh/additional", String.class) 则会报错
java.lang.IllegalStateException: No instances available for fanyi.baidu.com at org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.execute(RibbonLoadBalancerClient.java:105) ~[spring-cloud-netflix-ribbon-2.1.0.RELEASE.jar:2.1.0.RELEASE] at org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.execute(RibbonLoadBalancerClient.java:93) ~[spring-cloud-netflix-ribbon-2.1.0.RELEASE.jar:2.1.0.RELEASE] at org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor.intercept(LoadBalancerInterceptor.java:55) ~[spring-cloud-commons-2.1.0.RELEASE.jar:2.1.0.RELEASE] 官方针对这种情况给出的方案是创建两个RestTemplate,在不同的的情况下区分使用
@Configuration
public class MyConfiguration {
@LoadBalanced
@Bean
RestTemplate loadBalanced() {
return new RestTemplate();
}
@Primary
@Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
}
public class MyClass {
@Autowired
private RestTemplate restTemplate;
@Autowired
@LoadBalanced
private RestTemplate loadBalanced;
public String doOtherStuff() {
return loadBalanced.getForObject("http://stores/stores", String.class);
}
public String doStuff() {
return restTemplate.getForObject("http://example.com", String.class);
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
https://docs.spring.io/spring-cloud-commons/reference/spring-cloud-commons/common-abstractions.html#rest-template-loadbalancer-client https://blog.csdn.net/baozhutang/article/details/90236887