RestTemplate 应该是静态的全局声明吗?
2022-09-02 03:46:47
						我在我的代码中使用Java Callable Future。以下是我的主要代码,它使用future和可调用性 -
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();
    }
}
下面是我的类,它实现了可调用接口,我需要根据我们拥有的主机名生成URL,然后使用对服务器进行调用。如果第一个主机名中有任何异常,那么我将为另一个主机名生成URL,我将尝试进行调用。TaskRestTemplate
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
 
					 
				 
				    		 
				    		 
				    		