如何在多线程环境中有效使用RestTemplate?

如何在多线程环境中有效使用RestTemplate?,第1张

如何在多线程环境中有效使用RestTemplate?

如果我不明白您的问题,请纠正我。它似乎与这里的前一个非常相似。

在那里,我们确定这

RestTemplate
是线程安全的。因此,没有理由不在有意义的地方共享它。无论您在哪里以相同的方式使用它。您的示例似乎是执行此 *** 作的理想场所。

如您所述,

RestTemplate
为每个
Task
实例重新创建一个新实例是浪费的。

我将创建

RestTemplate
in
TimeoutThreadExample
并将其
Task
作为构造函数参数传递给the 。

class Task implements Callable<String> {    private RestTemplate restTemplate;    public Task(RestTemplate restTemplate) {        this.restTemplate = restTemplate;    }    public String call() throws Exception {        String url = "some_url";        String response = restTemplate.getForObject(url, String.class);        return response;    }}

这样,您可以

RestTemplate
在所有
Task
对象之间共享实例。

注意,

RestTemplate
用于
SimpleClientHttpRequestFactory
创建其连接。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5600777.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存