How to use RestTemplate efficiently in Multithreaded environment?

后端 未结 3 1350
耶瑟儿~
耶瑟儿~ 2020-12-08 02:42

I am working on a project in which I need to make a HTTP URL call to my server which is running Restful Service which returns back the response as a JSON String

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-08 03:25

    Correct me if I didn't understand your question. It seems very similar to the previous one here.

    There, we determined that RestTemplate is thread-safe. There is therefore no reason not to share it wherever it makes sense to, ie. wherever you are using it in the same way. Your example seems like the perfect place to do so.

    As you stated, recreating a new instance of RestTemplate for each Task instance is wasteful.

    I would create the RestTemplate in TimeoutThreadExample and pass it to the Task as a constructor argument.

    class Task implements Callable {
    
        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;
        }
    }
    

    This way you share the RestTemplate instance between all your Task objects.

    Note that RestTemplate uses SimpleClientHttpRequestFactory to create its connections.

提交回复
热议问题