【问题标题】:RestTemplate getForEntity method throws null pointer exceptionRestTemplate getForEntity 方法抛出空指针异常
【发布时间】:2020-07-15 18:45:50
【问题描述】:

我将 RestTemplate 与 Ribbon Client @LoadBalanced 一起使用。当我使用在两个实例上运行的 Discovery Server 调用我的服务时间服务(逻辑标识符)时,它会引发空指针异常。

我的两个时间服务实例运行正常。此外,在发现服务器中,两者都与此功能区客户端一起注册。

下面是相同的代码-

@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;
    }   

}

这是我在调用此服务时得到的堆栈跟踪 -

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)

这是Eureka仪表板的截图-

【问题讨论】:

  • 我知道什么是 NullPointerexception 以及如何修复它。但是,这里的问题是所有配置都已正确完成,但我无法弄清楚为什么我会得到 NPE。
  • 显然配置没有正确完成,否则您将无法获得空指针。您的调试日志说明了什么,并且在运行时调试了RibbonTimeAppApplication.getTime

标签: spring spring-boot resttemplate service-discovery netflix-ribbon


【解决方案1】:

您可以通过将 restTemplate 设为静态来避免此错误。请确认是否有效:

@Bean
@LoadBalanced
public static RestTemplate restTemplate() {
    return new RestTemplate();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-10
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    • 2020-08-10
    • 2013-03-21
    相关资源
    最近更新 更多