SpringCloud客户端负载均衡Ribbon

Bertha 。 2021-09-18 15:52 535阅读 0赞

上一篇写到关于SpringCloudEureka的相关知识:SpringCloud服务治理Eureka。我们实现的服注册中心,以及服务提供者。接下来记录关于服务消费,以及客户端负载均衡器Ribbon的简单使用和配置。在使用Ribbon之前,先看看怎么调用服务吧。

基础的服务消费

服务提供者

在上一篇的基础之上,创建一个service-user的微服务。这个微服我使用了h2数据库来保存数据,所以需要在配置文件中添加关于数据库的配置以及在pom文件中添加依赖,
application.yml

  1. server:
  2. port: 40000
  3. spring:
  4. application:
  5. name: user-service
  6. #===========================================================
  7. # 数据库配置
  8. #===========================================================
  9. jpa:
  10. show-sql: true
  11. hibernate:
  12. ddl-auto: none
  13. generate-ddl: false
  14. datasource:
  15. platform: h2
  16. schema: classpath:schema.sql
  17. data: classpath:data.sql
  18. #===========================================================
  19. # eureka配置
  20. #===========================================================
  21. eureka:
  22. client:
  23. serviceUrl:
  24. defaultZone: http://localhost:8888/eureka/
  25. instance:
  26. prefer-ip-address: true
  27. instance-id: ${spring.application.name}:${server.port}

pom.xml

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-jpa</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-web</artifactId>
  9. </dependency>
  10. <dependency>
  11. <groupId>org.springframework.cloud</groupId>
  12. <artifactId>spring-cloud-starter-eureka</artifactId>
  13. </dependency>
  14. <dependency>
  15. <groupId>com.h2database</groupId>
  16. <artifactId>h2</artifactId>
  17. <scope>runtime</scope>
  18. </dependency>
  19. </dependencies>

然后编写数据库文件初始化数据;
schema.sql

  1. DROP TABLE user if EXISTS ;
  2. create table user (
  3. id int generated by DEFAULT as IDENTITY,
  4. username VARCHAR (40),
  5. age INT(3),
  6. PRIMARY KEY (id)
  7. );

data.sql

  1. insert into user (id,username,age) values (1,'张三',20);
  2. insert into user (id,username,age) values (2,'李四',25);
  3. insert into user (id,username,age) values (3,'王五',23);
  4. insert into user (id,username,age) values (4,'赵六',30);

User实体类,这里使用了lombok工具

  1. @Entity
  2. @Data
  3. public class User implements Serializable {
  4. @Id
  5. @GeneratedValue(strategy = GenerationType.AUTO)
  6. private Long id;
  7. @Column
  8. private String username;
  9. @Column
  10. private int age;
  11. }

然后创建UserRepositoryUserController,在UserController中添加一个根据id查询的接口:

  1. @Autowired
  2. private UserRepository userRepository;
  3. @GetMapping("/user/{id}")
  4. public User findById(@PathVariable("id") Long id){
  5. return userRepository.findOne(id);
  6. }

SpringBoot入口类上添加@EnableEurekaClient注解

  1. @EnableEurekaClient
  2. @SpringBootApplication
  3. public class UserApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(UserApplication.class, args);
  6. }
  7. }

最终的项目结构:

10

启动项目,访问:http://localhost:40000/user/1
10 1

服务消费

这里直接修改上一篇service-article服务,用service-article服务来调用service-user服务。所以需要修改service-article,新增User对象和ArticleController,在ArticleController中添加一个查询接口。
这里调用服务都是使用RestTemplate,所以先在入口内中注册注册RestTemplate

  1. @SpringBootApplication
  2. @EnableEurekaClient
  3. public class ArticleApplication {
  4. @Bean
  5. public RestTemplate restTemplate(){
  6. return new RestTemplate();
  7. }
  8. public static void main(String[] args) {
  9. SpringApplication.run(ArticleApplication.class, args);
  10. }
  11. }

User实体,可以直接拷贝user微服务的实体类去掉注解即可,因为这里不是持久化对象。

  1. @Data
  2. public class User implements Serializable {
  3. private Long id;
  4. private String username;
  5. private int age;
  6. }

ArticleController

  1. @RestController
  2. public class ArticleController {
  3. @Autowired
  4. private RestTemplate restTemplate;
  5. @GetMapping("/a/u/{id}")
  6. public User getUser(@PathVariable("id") Long id){
  7. return restTemplate.getForObject("http://localhost:40000/user/{1}",User.class,id);
  8. }
  9. }

启动服务,访问:http://localhost:30000/a/u/2

使用Ribbon

介绍

SpringCloudRibbon是一个基于HTTP和TCP的客户端负载均衡工具。是基于Netfix Ribbon实现的。SpringCloud将其封装,可以让我们轻松的将面向服务的REST模板自动转换成客户端负载均衡的服务调用。

使用

修改article-service
添加依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>

在注册RestTemplate方法上添加@LoadBalanced注解开启客户端负载均衡,然后修改请求的URL,直接使用服务名请求,这里能够直接使用服务名,是因为在SpringCloudRibbon中有一个拦截器,他能够在实际调用的时候自动的选取服务实例,并将实际请求的ip地址替换这里的服务名。详细介绍可以查看DD大佬的书:<>

  1. @GetMapping("/a/u/{id}")
  2. public User getUser(@PathVariable("id") Long id){
  3. return restTemplate.getForObject("http://USER-SERVICE:40000/user/{1}",User.class,id);
  4. }

最后为了测试负载均衡,我们需要开启多个USER-SERVICE服务实例;在USER-SERVICE中添加application-pree1.ymlapplication-pree2.yml,具体配与application.yml一样,只要修改server.port,这里分别是40001和40002。然后打包服务,分别启动两个服务

  1. java -jar user-0.0.1-SNAPSHOT.jar --spring.profiles.active=pree1
  2. java -jar user-0.0.1-SNAPSHOT.jar --spring.profiles.active=pree2

在注册中心可以看到三个USER-SERVICE服务:
10 2
最后启动ARTICLE-SERVICE,并访问接口。刷新几次页面,发现三个服务都会打印数据库语句,这里调用方式为线性轮询
10 3

Ribbon的配置

当我们在SpringBoot项目中添加SpringCloudRibbon以后,SpringBoot会为我们自动化配置Ribbon,有些时候自动化配置是无法满足需要的。我们都知道在SpringBoot中我们可以使用两种配置属性的方法:使用java config方式和在配置文件中配置。

使用配置类的方式

创建UserServiceConfig,该类不能在启动时候被扫描到,所以我们需要将该类放到SpringBoot入口类的上一层路径下。

  1. @Configuration
  2. public class UserServiceConfig {
  3. /**
  4. *将服务检查策略改为PingUrl
  5. * @return
  6. */
  7. @Bean
  8. public IPing ribbonPing(){
  9. return new PingUrl();
  10. }
  11. /**
  12. * 将负载均衡的策略改为随机选取服务实例
  13. * @return
  14. */
  15. @Bean
  16. public IRule ribbonRule(){
  17. return new RandomRule();
  18. }
  19. }

然后创建RibbonConfig,这里@RibbonClients注解是可以指定多个RibbonClient,而@RibbonClient注解则是指定那个哪个服务使用哪个配置类

  1. @Configuration
  2. @RibbonClients({
  3. @RibbonClient(name = "user-service",configuration = UserServiceConfig.class),
  4. })
  5. public class RibbonConfig {
  6. }

在appplication.yml中配置

在配置文件中配置时候我们也可以配置全局的和指定客户端方式配置

  1. 全局配置,只需要使用ribbon.<key>=<value>,key客户端配置参数名,value为对应的参数值
  2. 指定客户端配置,使用<client>.ribbon.<key>=<value>,这里的client为指定的服务名。下面为user-service指定负载均衡策略:

    USER-SERVICE:
    ribbon:

    1. RulePredicateClasses: com.netflix.loadbalancer.RandomRule

更多关于key的配置信息可以查看com.netflix.client.config.CommonClientConfigKey


作为SpringCloud学习笔记,可能有很多地方不好。望指出!!!

源码地址:https://gitee.com/wqh3520/spring-cloud-1-9/tree/master/

原文地址:SpringCloud学习之Ribbon

发表评论

表情:
评论列表 (有 0 条评论,535人围观)

还没有评论,来说两句吧...

相关阅读