Netflix:服务的消费与提供
图
微服务中最重要的就是服务的创建和消费问题,既然各个模块拆分为了每个独立的模块,那么模块之间的通信就是使之联系起来的关键,只有解决了每个服务之间的通信,才能实现各个服务之间的调用

问题

当一个微服务完成了某个功能,给其他微服务的应用进行调用,两个微服务之间如何通信?

解决

当某个微服务需要调用其他微服务时,可使用RestTemplate以HTTP的RESTful的形式去调用

RestTemplate无法直接注入,创建配置类

@Configuration
public class RestConfigBean {

    @Bean
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }

}

然后就可以调用其他服务了

@Resource
private RestTemplate restTemplate;

@RequestMapping("/test")
public User test() {

    return restTemplate.getForObject("http://localhost:8001/hello", User.class);

}