Ribbon从入门到源码解析

本文介绍了Ribbon在Spring Cloud中作为客户端负载均衡器的使用,通过搭建EurekaServer、order-service和user-service展示Ribbon的工作流程。详细解析了Ribbon如何拦截请求、解析服务名、获取服务信息以及根据负载均衡策略选择服务。同时,对Ribbon的源码进行了简单解析,包括ILoadBalancer、AbstractLoadBalancer、BaseLoadBalancer、DynamicServerListLoadBalancer和ZoneAwareLoadBalancer等关键类的作用和实现。
摘要由CSDN通过智能技术生成

目录

1、简介

2、案例

2.1 搭建服务注册中心EurekaServer

2.2 搭建order-service服务

2.3 搭建user-service服务

2.4 服务启动

2.5 测试结果

3、Ribbon如何实现负载均衡

3.1 拦截http请求

3.2 解析请求中的服务名

3.3 根据服务名获取服务IP和Port信息

3.4 根据负载均衡策略发起http请求

4、简单源码解析

4.1 ILoadBalancer

4.2 AbstractLoadBalancer

4.3 BaseLoadBalancer

4.4 DynamicServerListLoadBalancer

4.5 ZoneAwareLoadBalancer


1、简介

在微服务架构中,服务拆分成一个个的微服务,并且以集群化的方式进行部署;此时服务与服务之间的调用变得复杂了起来,客户端需要自主选择调用服务端集群中的某个服务,这就是我们经常说到的客户端负载均衡,在Spring Cloud生态中使用的比较广泛的技术是Ribbon。

2、案例

无论是使用Fegin还是RestTemplate发起服务调用,客户端负载均衡均是通过Ribbon来实现,这里使用RestTemplate演示案例。

2.1 搭建服务注册中心EurekaServer

  • pom依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
  • application.yml

server:
  port: 18888

spring:
  application:
    name: eurekaServer

eureka:
  client:
#    fetch-registry: false
#    register-with-eureka: false
    service-url:
      defaultZone: http://127.0.0.1:18888/eureka
  • 启动类

@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }

}

2.2 搭建order-service服务

  • pom依赖

<!--web-->
<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--EurekaClient-->
<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
  • application.yml

# server port
server:
  port: 18070

# name
spring:
  application:
    name: order-service

# eureka server
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:18888/eureka
  • 模拟业务代码

@RestController
@RequestMapping("order")
public class OrderController {
    
    @Autowired
    private OrderService orderService;
    
    @GetMapping("{orderId}")
    public Order queryOrderByUserId(@PathVariable("orderId") Long orderId) {
        // 根据id查询订单并返回
        return orderService.queryOrderById(orderId);
    }
}
@Service
public class OrderService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private OrderMapper orderMapper;

    public Order queryOrderById(Long orderId) {
        // 1.查询订单
        Order order = orderMapper.findById(orderId);
        // 2、查询用户信息
        if (Objects.nonNull(order)) {
            String url = String.format("http://user-service/user/%s", order.getUserId());
            User user = restTemplate.getForObject(url, User.class);
            // 3、封装用户信息
            order.setUser(user);
        }
        // 4.返回
        return order;
    }
}
  • 启动类中注入RestTemplate并开启负载均衡

@MapperScan("com.lzb.order.mapper")
@SpringBootApplication
@EnableEurekaClient
public class OrderApplication {

    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class, args);
    }

    /**
     * RestTemplate bean容器的注入
     * LoadBalanced 负载均衡注解
     * @return
     */
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

}

2.3 搭建user-service服务

  • pom依赖

<!--web-->
<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--EurekaClient-->
<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

  • application.yml

# server port
server:
  port: 18080

# name
spring:
  application:
    name: user-service

# eureka server
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:18888/eureka

  • 模拟业务代码

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public User queryById(@PathVariable("id") Long id) {
        return userService.queryById(id);
    }
}

  • 启动类

@MapperScan("com.lzb.user.mapper")
@SpringBootApplication
@EnableEurekaClient
public class UserApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserApplication.class, args);
    }
}

2.4 服务启动

在上述服务搭建之后,可以看出order-service服务调用了user-service服务,因此我将user-service服务集群部署,并且在order-service注入了RestTemplate且标注了LoadBalanced注解;启动顺序如下所示:

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李子捌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>