HttpClient的并发性单例

问题描述 投票:0回答:2

我使用Spring Boot并创建了一个服务(微服务设计的一部分)。我有以下方法,

public static HttpClient getHttpClient() throws KeyManagementException, NoSuchAlgorithmException {

        log.info("Creating Http Client...");
        final SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                new SSLContextBuilder().build());
        final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(200);
        connectionManager.setDefaultMaxPerRoute(20);

        return HttpClients.custom()
                .disableRedirectHandling()
                .setSSLSocketFactory(sslConnectionSocketFactory)
                .setConnectionManager(connectionManager)
                .build();
    }

我多次调用此方法,只想维护一个实例并在创建后重新使用它。考虑到并发编程,我可以使用单例模式吗?而且我看到RestTemplate是一种非常好的方法,而不是按照下面的链接而不是Apache Http Client,

RestTemplate vs Apache Http Client for production code in spring project

建议深表感谢。

spring-boot design-patterns java-8 apache-httpclient-4.x
2个回答
1
投票

我建议您使用spring RestTemplate。在您的应用程序中仅实例化一次RestTemplate实例,然后使用依赖注入在多个服务/组件类中使用它。

创建RestTemplate实例的最佳方法是将其注册为spring配置类中的spring bean。这将在应用程序启动时创建RestTemplate实例。下面的代码将创建RestTemplate的单个实例,并且可以在多个类之间共享。

@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
//if you want to set any properties in RestTemplate, set here
return restTemplate;
}

现在可以在任何服务类中使用RestTemplate,请使用依赖项注入:

@Service
class TestService {

@Autowired
private RestTemplate restTemplate

public void invokeRemoteService(){
//Here you are using restTemplate 
  String response = 
      restTemplate.postForObject(url, request, String.class);
}

}

0
投票

首先,您应该使用spring核心的依赖注入,而不是直接使用方法来使实例在Spring中工作。依赖项注入(DI)容器将为您生成所需的实例并将其注入。这样,您可以通过设置范围或使用特殊注释来配置DI容器多长时间生成一次实例。可以在这里找到带有自定义范围的DI中代码示例的很好解释:https://www.baeldung.com/spring-bean-scopes

第二,我建议使用Spring RestTemplate并通过RestTemplateBuilder或RestTemplateCustomizer根据您的需求进行配置https://www.baeldung.com/spring-rest-template-builder有了RestTemplate,spring已经提供了很多Test设置类,使开箱即用的JUnit测试变得容易,如果已经在spring框架内工作,建议使用spring提供的选项。

© www.soinside.com 2019 - 2024. All rights reserved.