Spring Cloud Commons模块

  上一篇介绍了 Spring Cloud Context模块 ,本文介绍SpringCloud的另一个基础模块 SpringCloud Commons模块 。只要在项目的pom文件中引入了spring-cloud-starter 依赖包 ,就可以保证 spring-cloud-commons 的 jar被引入。

       Spring Cloud Commons模块设计的目的,Spring Cloud Commons模块是为了对微服务中的服务注册与发现、负载均衡、熔断器等功能提供一个抽象层代码,这个抽象层与具体的实现无关。这样这些功能具体的实现上可以采用不同的技术去实现,并可以做到在使用时灵活的更换。

       下面是一些常用的抽象点:

  1. @EnableDiscoveryClient

          该注解是用来在META-INF/spring.factorie文件中查找DiscoveryClient接口的实现类,并以bean的形式加载到Spring的IOC容器中。在使用的时候会把这个注解加在SpringBoot的main类上。但这个注解在目前springCloud的Greenwich版本上已经不再需要了(也就是可有可无),只要引入具体的DiscoveryClient接口的jar依赖就可以,因为具体实现包上会通过自动配置类进行设置。

       2. ServiceRegistry接口

          这个接口提供注册Registration与撤销Registration的注册的方法。这里的Registration是一个标记接口 ,用来描述一个服务实例,具体包含关于实例的信息,比如它的主机名和端口等信息。

       3. 让Spring RestTemplate具备负载均衡功能

   创建RestTemplate的Bean时使用@LoadBalanced注解, 就可以自动配置为使用ribbon。如下面的示例所示:

@Configuration
public class MyConfiguration {

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

public class MyClass {
    @Autowired
    private RestTemplate restTemplate;

    public String doOtherStuff() {
//注意:代码中的url要使用服务名,而不是主机名 String results
= restTemplate.getForObject("http://stores/stores", String.class); return results; } }

 

    

posted @ 2019-03-19 23:39  杭州胡欣  阅读(10372)  评论(0编辑  收藏  举报