线程" main"中的例外情况java.lang.NullPointerException com.javainuse.controllers.ConsumerControllerClient.getEmployee(ConsumerControllerClient)

时间:2018-04-07 11:09:58

标签: java spring-boot microservices spring-cloud

我已经从http://www.javainuse.com/spring/spring_ribbon获取了参考资料,但尚未进行任何自定义。我能够运行eureka-server,只需在下面添加

server.port=8090
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
spring.application.name=eureka-server

我也有员工生产者也运行良好

application.properties

eureka.client.serviceUrl.defaultZone=http://localhost:8090/eureka
eureka.instance.instanceId=${spring.application.name}:${random.value}

bootstrap.properties

spring.application.name=employee-producer
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

当我尝试运行员工消费者时,我遇到了错误 强文 ConsumerControllerClient

@Controller
public class ConsumerControllerClient {

    @Autowired
    private LoadBalancerClient loadBalancer;

    public void getEmployee() throws RestClientException, IOException {

        ServiceInstance serviceInstance=loadBalancer.choose("employee-producer");

        System.out.println(serviceInstance.getUri());

        String baseUrl=serviceInstance.getUri().toString();

        baseUrl=baseUrl+"/employee";

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response=null;
        try{
        response=restTemplate.exchange(baseUrl,
                HttpMethod.GET, getHeaders(),String.class);
        }catch (Exception ex)
        {
            System.out.println(ex);
        }
        System.out.println(response.getBody());
    }

    private static HttpEntity<?> getHeaders() throws IOException {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
        return new HttpEntity<>(headers);
    }
}

我得到的错误是

Exception in thread "main" java.lang.NullPointerException
    at com.javainuse.controllers.ConsumerControllerClient.getEmployee(ConsumerControllerClient.java:28)
    at com.javainuse.SpringBootHelloWorldApplication.main(SpringBootHelloWorldApplication.java:21)

SpringBootHelloWorldApplication

@SpringBootApplication
public class SpringBootHelloWorldApplication {

    public static void main(String[] args) throws RestClientException, IOException {
        ApplicationContext ctx = SpringApplication.run(SpringBootHelloWorldApplication.class, args);

        ConsumerControllerClient consumerControllerClient = ctx.getBean(ConsumerControllerClient.class);
        System.out.println(consumerControllerClient);
        consumerControllerClient.getEmployee();

    }

    @Bean
    public ConsumerControllerClient consumerControllerClient() {
        return new ConsumerControllerClient();
    }
}

0 个答案:

没有答案