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

AKI*_*WEB 15 java multithreading callable resttemplate

我在我的代码中使用Java Callable Future.下面是我使用未来和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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Sot*_*lis 18

无论是哪种方式,都是无关紧要的static.

RestTemplate用于发出HTTP请求的方法是线程安全的,因此无论您是RestTemplate每个Task实例还是所有Task实例的共享实例都是无关紧要的(垃圾收集除外).

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

  • "就我个人而言,我会创建......"或使用依赖注入;)+1 (3认同)
  • @Rc 是的,这就是我的意思,尽可能控制反转。如果可能的话也使用 DI 容器。 (2认同)