我有一个实现了4个微服务的系统。这四个服务需要偶尔共享信息,它们通过使用Spring的RestTemplate进行RESTful请求来实现。目前,大约5%-10%的请求会失败,并出现如下异常:
org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://otherservice.com/path": Connection reset; nested exception is java.net.SocketException: Connection reset
再次出现这种情况似乎是随机的,只有5%-10%的几率会出错。我已经尝试了多种方法,但没有什么效果。目前,我正在尝试以下方法:
配置:
@Configuration
public class BeanConfiguration {
@Bean
public RestTemplate restTemplate() {
ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(HttpClients.createDefault());
return new RestTemplate(requestFactory);
}
}
服务:
@Autowired
public MyService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public Contact addContact(Contact contact) {
HttpEntity<Contact> entity = new HttpEntity<>(contact, authenticationTokenInfo.setTokenHeaders());
ResponseEntity<Contact> response = restTemplate.exchange(contact_base_url, HttpMethod.POST, entity, Contact.class);
return response.getBody();
}
我尝试了许多不同的方法,但都没有任何效果。比如说,我尝试了以下方法:
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
我正在记录每个微服务的所有请求,但似乎这些请求实际上没有到达其他服务。它们只是失败了。根据日志,它们在不到50毫秒的时间内失败,因此这不是超时问题。对于其中的一些,我已经实现了指数级退避重试,但这并不是一个可行的解决方案。