SpringCloudCommons模块
  上⼀篇介绍了,本⽂介绍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;
spring ioc注解
public String doOtherStuff() {
//注意:代码中的url要使⽤服务名,⽽不是主机名
String results = ForObject("stores/stores", String.class);
return results;
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。