主要原因
是因为使用了负载均衡注解@LoadBalanced,加上负载均衡注解后,就会去注册中心寻找服务。因为是第三方的服务(或,用的是ip,而不是实例名;或,自己的项目并没有注册到eureka),所以报找不到实例的异常。
@Bean @LoadBalanced public RestTemplate restTemplate(ClientHttpRequestFactory clientHttpRequestFactory) { // boot中可使用RestTemplateBuilder.build创建 RestTemplate restTemplate = new RestTemplate(); modifyDefaultCharset(restTemplate); // 配置请求工厂 restTemplate.setRequestFactory(clientHttpRequestFactory); return restTemplate; }private void modifyDefaultCharset(RestTemplate restTemplate) { List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters(); HttpMessageConverter<?> converterTarget = null; for (HttpMessageConverter<?> item : converterList) { if (StringHttpMessageConverter.class == item.getClass()) { converterTarget = item; break; } } if (null != converterTarget) { converterList.remove(converterTarget); } Charset defaultCharset = Charset.forName("utf-8"); converterList.add(1, new StringHttpMessageConverter(defaultCharset)); }
解决方案
1、不使用@Autowired自动装载的restTemplate直接new RestTemplate()
new RestTemplate()
2、使用其他方法发送三方请求如httpClient
public class HttpClientUtil { protected static final Logger log = LoggerFactory.getLogger(HttpClientUtil.class); public static String sendPostJson(String jsonParm, String url) throws Exception { String result = null; CloseableHttpClient httpclient = null; HttpPost httppost = null; HttpResponse response = null; try { httpclient = HttpClients.createDefault(); httppost = new HttpPost(url); StringEntity entity = new StringEntity(jsonParm, "utf-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); httppost.setEntity(entity); response = httpclient.execute(httppost); result = EntityUtils.toString(response.getEntity(), "UTF-8"); httppost.abort(); } catch (Exception e) { log.error("请求地址-->" + url); log.error("请求参数-->" + jsonParm); throw e; } finally { if (httpclient != null) { try { httpclient.close(); } catch (IOException e) { throw new Exception(e); } } } return result; } }