【问题标题】:Concurrency of a HttpClient in a singleton单例中 HttpClient 的并发性
【发布时间】:2020-02-04 13:47:47
【问题描述】:

我使用 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

非常感谢您的建议。

【问题讨论】:

  • 你可以只创建一个bean

标签: spring-boot design-patterns java-8 apache-httpclient-4.x


【解决方案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);
}

}

【讨论】:

    【解决方案2】:

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

    其次,我建议使用 Spring RestTemplate 并通过 RestTemplateBuilder 或 RestTemplateCustomizer 配置它以满足您的需求 https://www.baeldung.com/spring-rest-template-builder 借助 RestTemplate,spring 已经提供了很多测试设置类,使 JUnit 测试开箱即用,如果您已经在 spring 框架中工作,建议使用 spring 提供的选项。

    【讨论】:

    • 不错,一定要使用 DI。肯定会调查的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多