1.什么是Ribbon
是 Netflix 发布的一个负载均衡器,有助于控制 HTTP 和 TCP客户端行为。在 SpringCloud 中, nacos一般配合Ribbon进行使用,Ribbon提供了客户端负载均衡的功能,Ribbon利用从nacos中读 取到的服务信息,在调用服务节点提供的服务时,会合理(策略)的进行负载。 在SpringCloud中可以将注册中心和Ribbon配合使用,Ribbon自动的从注册中心中获取服务提供者的 列表信息,并基于内置的负载均衡算法,请求服务。
是 Netflix 发布的一个负载均衡器,Ribbon自动的从注册中心中获取服务提供者的 列表信息,并基于内置的负载均衡算法,请求服务。
2.Ribbon的主要作用
(1)服务调用
基于Ribbon实现服务调用, 是通过拉取到的所有服务列表组成(服务名-请求路径的)映射关系。借助 RestTemplate 最终进行调用
(2)负载均衡
当有多个服务提供者时,Ribbon可以根据负载均衡的算法自动的选择需要调用的服务地址
Ribbon是Spring Cloud的一个组件, 它可以让我们使用一个注解就能轻松的搞定负载均衡
第1步:在RestTemplate 的生成方法上添加@LoadBalanced注解
@Bean
@LoadBalanced //策略轮询
public RestTemplate getRestTemplate() { return new RestTemplate(); }
第2步:修改服务调用的方法
package com.cyy.order.controller;
import com.cyy.coment.entry.Order;
import com.cyy.coment.entry.Product;
import com.cyy.order.sevice.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;
/**
* @program: springcloud-parent
* @description: 订单的控制层
* @author: 崔艺耀
* @create: 2021-07-06 19:50
**/
@RestController
@RequestMapping("order")
public class OrderController {
@Autowired
private OrderService orderService;
@Autowired
private RestTemplate restTemplate;
@GetMapping("saveOrder")
public String saveOrder(@RequestParam Integer pid,Integer num){
Order order=new Order();
order.setNumber(num);
order.setUid(2);
order.setUsername("张三");
order.setPid(pid);
Product product = restTemplate.getForObject("http://product/product/FindById/"+pid, Product.class);
order.setPname(product.getPname());
order.setPprice(product.getPprice());
orderService.saveOrder(order);
return "下单成功";
}
}
Ribbon支持的负载均衡策略
Ribbon内置了多种负载均衡策略,内部负载均衡的顶级接口为
com.netflix.loadbalancer.IRule , 具体的负载策略如下图所示: