Spring Cloud与Docker微服务架构实战简单学习笔记(二)
Eureka与Ribbon配合使用架构图
1. 如何使用Ribbon负载均衡
1.1 引入依赖包
<!-- 添加Ribbon依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
如果已经引入“spring-cloud-starter-eureka”包,该包已经包含了“spring-cloud-starter-ribbon”,所以无需再次引入。
1.2 添加@LoadBalanced注解
为RestTemplate添加@LoadBalanced注解:
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
1.3 通过服务名调用接口
之前用IP、端口访问,代码如下:
@GetMapping("/user/{id}")
public UserEntity findBiId(@PathVariable Long id) {
return this.restTemplate.getForObject("http://localhost:3131/user/"+id, UserEntity.class);
}
现在可以改为用服务名调用,ribbon做负载均衡:
@GetMapping("/user/{id}")
public UserEntity findBiId(@PathVariable Long id) {
return this.restTemplate.getForObject("http://microservice-simple-provider-user/user/"+id, UserEntity.class);
}
以上步骤操作完以后,就有了负载均衡,规则是轮流调用,服务提供者user1、user2、user1…。
接下来学习如何改变ribbon的负载均衡规则。
2. 使用Java代码修改Ribbon负载均衡规则
在springcloud中,Ribbon默认的配置类是RibbonClientConfiguration。
2.1 创建一个Ribbon的配置类
@Configuration
public class RibbonConfiguration {
@Bean
public IRule ribbonRule() {
// 负载均衡规则,改为随机
return new RandomRule();
}
}
2.2 创建一个空类,在其上添加@Configuration和@RibbonClient注解
@Configuration
@RibbonClient(name="microservice-simple-provider-user", configuration = RibbonConfiguration.class)
public class TestConfiguration {
}
重启服务消费者movie,可以看到变成随机调用user1和user2了。
注意:
本例中的RibbonConfiguration类不能包含在主应用程序上下文的@ComponentScan中,否则该类中的配置信息就被所有的@RibbonClient共享。(即所有的调用的服务方负载均衡规则都为随机)
因此,如果只想自定义某一个Ribbon客户端的配置,必须防止@Configuration注解的类所在的包与@ComponentScan扫描的包重叠,或显示指定@ComponentScan不扫描@Configuration类所在的包。
在本例中,如果不加那个空类,则所有负载均衡都改为随机,如果加了空类,就指定只有“microservice-simple-provider-user”才为随机。
3. 使用属性自定义Ribbon配置
上面用Java代码改变负载均衡规则有点麻烦,现在演示用配置的方式改变负载均衡规则。
3.1 添加配置
配置的前置为:<clientName>.ribbon
microservice-simple-provider-user.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RandomRule
4. 脱离Eureka使用Ribbon
4.1 properties添加配置项即可
microservice-simple-provider-user.ribbon.listOfServer=localhost:3131,localhost:3132