【问题标题】:How does resttemplate.exchange() execute on a different thread?resttemplate.exchange() 如何在不同的线程上执行?
【发布时间】:2019-08-14 17:19:46
【问题描述】:

据我了解,调用 resttemplate 的 exchange 方法是在不同的线程上执行的。基本上所有客户端库都在不同的线程上执行。

假设我的 servlet 容器是 tomcat。当向暴露的端点发出请求时,tomcat 线程接收请求,并且请求从同一线程上的控制器层到达服务层。在服务层,我使用 resttemplate 调用了 3rd 方服务。当调用exchange方法时,内部操作在不同的线程上运行并获取操作的结果。

我对此有疑问:

resttemplate 基本上从哪个线程池中获取线程以在不同的线程上执行?

我想知道在不同线程上执行 resttemplate 是否必须对 tomcat 线程池做任何事情。

有人能解释一下吗?

【问题讨论】:

    标签: multithreading spring-boot spring-mvc threadpool resttemplate


    【解决方案1】:

    当向暴露的端点发出请求时,tomcat 线程会收到 请求和请求从控制器到达服务层 层在同一个线程上。

    只有当 tomcat 和 java 应用程序在同一个 JVM 中时才会发生这种情况(比如在嵌入式 tomcat 中)。否则,默认情况下,Java 线程被创建和销毁而不被池化。当然,你也可以创建一个java线程池。

    每次通过 RestTemplate 调用第三方 API 时,它都会创建新的 Httpconnection 并在完成后将其关闭。您可以像这样使用HttpComponentsClientHttpRequestFactory 创建 RestTemplate 自己的连接池:

    new org.springframework.web.client.RestTemplate(new HttpComponentsClientHttpRequestFactory())
    

    【讨论】:

    • 谢谢,这很有帮助
    猜你喜欢
    • 2023-03-27
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多