0

I am using RestTemplate with Ribbon Client @LoadBalanced. When I am calling my service - time-service(logical identifier) using Discovery Server, which is running on two instances, it is throwing null pointer exception.

My two instances of time-service are running properly. Also, in discovery server both are registered along with this Ribbon client.

Below is the code for same -

@SpringBootApplication
@RestController
@EnableDiscoveryClient
public class RibbonTimeAppApplication {

    @Inject
    private RestTemplate restTemplate;
    
    public static void main(String[] args) {
        SpringApplication.run(RibbonTimeAppApplication.class, args);
    }
    
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
    
    @GetMapping
    public String getTime()
    {
        String response = "";
        try {
            response = restTemplate.getForEntity("http://time-service", String.class).getBody();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return response;
    }   

}

Here is the stacktrace I am getting when calling this service -

java.lang.NullPointerException
    at com.javatechstack.RibbonTimeAppApplication.getTime(RibbonTimeAppApplication.java:37)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at .......
.........................
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

This is the screenshot of Eureka dashboard -

enter image description here

vikash singh
  • 1,479
  • 1
  • 19
  • 29
  • Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Jens Jul 15 '20 at 18:50
  • I know what is NullPointerexception and how to fix it. But, here the issue is all the configurations are done properly but I am not able to figure out why I am getting the NPE. – vikash singh Jul 15 '20 at 19:11
  • apparently the configuration is not done properly otherwise you wouldn't have gotten the nullpointer. What does your debug logs say, and have ju debugged the `RibbonTimeAppApplication.getTime` during runtime? – Toerktumlare Jul 15 '20 at 23:20

1 Answers1

0

You can avoid this error by making restTemplate static. Please confirm if it works:

@Bean
@LoadBalanced
public static RestTemplate restTemplate() {
    return new RestTemplate();
}
Umesh Sanwal
  • 681
  • 4
  • 13