Spring Boot RestTemplate 随机 ResourceAccessException:连接重置错误

Gre*_*ash 5 resttemplate spring-boot

我有一个实现 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
Run Code Online (Sandbox Code Playgroud)

同样,这看起来是随机的,并且只有大约 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
Run Code Online (Sandbox Code Playgroud)

服务:

@Configuration
public class BeanConfiguration {

    @Bean
    public RestTemplate restTemplate() {
        ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(HttpClients.createDefault());
        return new RestTemplate(requestFactory);
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试了许多不同的方法,但没有任何区别。我试过这个例如:

@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();
}
Run Code Online (Sandbox Code Playgroud)

我正在记录每个微服务中的所有请求,但这些请求似乎并未真正影响其他服务。他们只是失败了。根据日志,它们在不到 50 毫秒内失败,因此这不是超时问题。对于其中一些,我实施了指数退避重试,但这并不是真正可行的解决方案。

jhe*_*a-d 0

我也面临同样的问题。问题似乎出在池中的空闲连接上。这解决了我的问题,并且偶尔不会发生任何错误

     HttpClient httpClient = HttpClients
                .custom()
                .evictIdleConnections(60000, TimeUnit.MILLISECONDS)
                .build();

    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
Run Code Online (Sandbox Code Playgroud)