RestTemplate应该是全局声明的静态吗

RestTemplate应该是全局声明的静态吗

本文介绍了RestTemplate应该是全局声明的静态吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的代码中使用Java Callable Future。下面是我使用未来和callables的主要代码 -

I am using Java Callable Future in my code. Below is my main code which uses the future and callables -

public class TimeoutThread {

    public static void main(String[] args) throws Exception {

        ExecutorService executor = Executors.newFixedThreadPool(5);
        Future<String> future = executor.submit(new Task());

        try {
            System.out.println("Started..");
            System.out.println(future.get(3, TimeUnit.SECONDS));
            System.out.println("Finished!");
        } catch (TimeoutException e) {
            System.out.println("Terminated!");
        }

        executor.shutdownNow();
    }
}

以下是我的任务实现Callable接口的类,我需要根据我们拥有的主机名生成URL,然后使用 RestTemplate 调用SERVERS。如果第一个主机名中有任何异常,那么我将为另一个主机名生成URL,我将尝试拨打电话。

Below is my Task class which implements the Callable interface and I need to generate URL depending on the hostname we have and then make a call to SERVERS using RestTemplate. If there is any exception in the first hostname, then I will generate URL for another hostname and I will try making a call.

class Task implements Callable<String> {
    private static RestTemplate restTemplate = new RestTemplate();

    @Override
    public String call() throws Exception {

    //.. some code

    for(String hostname : hostnames)  {
            if(hostname == null) {
                continue;
            }
            try {
                String url = generateURL(hostname);
                response = restTemplate.getForObject(url, String.class);

                // make a response and then break
                break;

            } catch (Exception ex) {
                ex.printStackTrace(); // use logger
            }
        }
    }
}

所以我的问题是我应该将 RestTemplate 声明为静态全局变量吗?或者它在这种情况下不应该是静态的?

So my question should I declare RestTemplate as static global variable? Or it should not be static in this scenario?

推荐答案

无论哪种方式无关紧要, static 或实例。

It doesn't matter either way, static or instance.

RestTemplate 用于发出HTTP请求的方法是线程安全的,所以是否每个任务实例都有 RestTemplate 实例或所有任务的共享实例实例是无关紧要的(垃圾收集除外)。

RestTemplate's methods for making HTTP requests are thread safe so whether you have a RestTemplate instance per Task instance or a shared instance for all Task instances is irrelevant (except for garbage collection).

就个人而言,我会创建 RestTemplate 任务类之外,并将其作为参数传递给任务构造函数。 (尽可能使用控制反转。)

Personally, I would create the RestTemplate outside the Task class and pass it as an argument to a Task constructor. (Use Inversion of Control whenever possible.)

这篇关于RestTemplate应该是全局声明的静态吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 02:09