定义 java.net.http.HttpClient 实例属性是一个好习惯吗?

发布于 2025-01-14 20:26:57 字数 1185 浏览 3 评论 0原文

我正在使用 JDK HttpClient 发出一些异步 HTTP 请求。特别是,我有一个类似于以下类的类:

public class MyClass {
  private HttpClient client;

  public MyClass(){
    client = HttpClient.newBuilder()
    .version(Version.HTTP_1_1)
    .connectTimeout(Duration.ofSeconds(20))
    .build();
  }
  
  public void send(String url){
    HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create(url))
    .header("Content-Type", "application/json")
    .POST(BodyPublishers.ofFile(Paths.get("file.json")))
    .build();
    client.sendAsync(request, BodyHandlers.ofString())
    .thenApply(HttpResponse::body)
    .thenAccept(System.out::println); 
  }
}

这样,当调用 send 方法时,我将重用 client 属性。根据文档,这是有效的,因为:“一旦构建,HttpClient 就是不可变的,并且可用于发送多个请求”。

除此之外,我还有一个内存缓存,用于保存 MyClass 的实例。我想知道这是否是一个好的做法。我特别想知道在内存中保留对 HttpClient 客户端属性的引用是否可能会导致任何类型的内存泄漏或问题,例如提到的 此处

例如,这可能是释放/结束用于执行异步请求的线程执行器的问题吗?

I'm using JDK HttpClient to make some asynchronous HTTP requests. In particular I have a class similar to the following one:

public class MyClass {
  private HttpClient client;

  public MyClass(){
    client = HttpClient.newBuilder()
    .version(Version.HTTP_1_1)
    .connectTimeout(Duration.ofSeconds(20))
    .build();
  }
  
  public void send(String url){
    HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create(url))
    .header("Content-Type", "application/json")
    .POST(BodyPublishers.ofFile(Paths.get("file.json")))
    .build();
    client.sendAsync(request, BodyHandlers.ofString())
    .thenApply(HttpResponse::body)
    .thenAccept(System.out::println); 
  }
}

This way, when invoking to the send method I'm reusing the client attribute. According to the doc this is valid because: "Once built, an HttpClient is immutable, and can be used to send multiple requests".

Together with this I have an in-memory cache where I'm keeping instances of MyClass. I would like to know if this is a good practice or not. In particular I would like to know if retaining those references to the HttpClient client attribute in memory may cause any kind of memory leak or problem like the one mentioned here.

Could this for example be a problem for releasing/ending the thread executor that is used for executing asynchronous requests?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文