SpringCloud 05 - Consul 服务注册与发现
1. 概述
1.1 简介
Spring Cloud Ribbon 是基于 Netflix Ribbon 实现的一套客户端负载均衡的工具。
简单的说,Ribbon 是 Netflix 发布的开源项目,主要功能是提供客户端的软件负载均衡算法和服务调用。Ribbon 客户端组件提供一系列完善的配置项 如连接超时,重试等。简单的说,就是在配置文件中列出 Load Balancer (简称LB) 后面所有的机器,Ribbon 会自动的帮助你基于某种规则(如简单轮询,随机连接等)去连接这些机器。我们很容易使用 Ribbon 实现自定义的负载均衡算法。
1.2 官网:
Ribbon目前也进入维护模式:
1.3 作用
LB(负载均衡)
① LB 负载均衡(Load Balance)是什么
简单的说就是将用户的请求平摊的分配到多个服务上,从而达到系统的 HA (高可用)。
常见的负载均衡有软件 Nginx,LVS,硬件 F5 等。
② Ribbon 本地负载均衡客户端 VS Nginx 服务端负载均衡区别
Nginx 是服务器负载均衡,客户端所有请求都会交给 nginx,然后由 nginx 实现转发请求。即负载均衡是由服务端实现的。
Ribbon 本地负载均衡,在调用微服务接口时候,会在注册中心上获取注册信息服务列表之后缓存到 JVM本地,从而在本地实现 RPC 远程服务调用技术。
③ LB(负载均衡)分类:
- 集中式 LB:即在服务的消费方和提供方之间使用独立的 LB 设施(可以是硬件,如 F5,也可以是软件,如 nginx),由该设施负责把访问请求通过某种策略转发至服务的提供方;
- 进程内 LB:将 LB 逻辑集成到消费方,消费方从服务注册中心获知有哪些地址可用,然后自己再从这些地址中选择出一个合适的服务器。Ribbon 就属于进程内LB,它只是一个类库,集成于消费方进程,消费方通过它来获取到服务提供方的地址。
一句话:负载均衡 + RestTemplate调用
2. Ribbon 负载均衡演示
2.1 架构说明
Ribbon 在工作时分成两步:
- 第一步先选择 EurekaServer,它优先选择在同一个区域内负载较少的 server。
- 第二步再根据用户指定的策略,在从 server 取到的服务注册列表中选择一个地址。其中 Ribbon 提供了多种策略:比如轮询、随机和根据响应时间加权。
总结:Ribbon其实就是一个软负载均衡的客户端组件, 他可以和其他所需请求的客户端结合使用,和 Eureka 结合只是其中一个实例.
2.2 POM
如果已经带了新版的 Eureka 的依赖,就不用再加 Ribbon 的依赖了,因为 Eureka 中已经集成了 Ribbon
2.3 二说RestTemplate的使用
① 官网
② getForObject 方法 / getForEntity 方法
@GetMapping("/consumer/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
}
@GetMapping("/consumer/payment/getForEntity/{id}")
public CommonResult<Payment> getPaymentById2(@PathVariable("id") Long id) {
ResponseEntity<CommonResult> forEntity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
if(forEntity.getStatusCode().is2xxSuccessful())
return forEntity.getBody();
else
return new CommonResult<>(444,"操作失败");
}
③ postForObject / postEntity
3. Ribbon 核心组件 IRule
3.1 IRule:根据特定算法从服务列表中选取一个要访问的服务
- com.netflix.loadbalancer.RoundRobinRule:轮询
- com.netflix.loadbalancer.RandomRule:随机
- com.netflix.loadbalancer.RetryRule:先按照 RoundRobinRule 的策略获取服务,如果获取服务失败则在指定时间内进行重试,获取可用的服务
- WeightedResponseTimeRule:对 RoundRobinRule 的扩展,响应速度越快的实例选择权重越多大,越容易被选择
- BestAvailableRule:会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量最小的服务
- AvailabilityFilteringRule:先过滤掉故障实例,再选择并发较小的实例
- ZoneAvoidanceRule:默认规则,复合判断 server 所在区域的性能和 server 的可用性选择服务器
3.2 如何替换
① 修改cloud-consumer-order80
② 注意配置细节
官方文档明确给出了警告:
这个自定义配置类不能放在 @ComponentScan 所扫描的当前包下以及子包下,否则我们自定义的这个配置类就会被所有的 Ribbon客户端所共享,达不到特殊化定制的目的了。
③ 新建package:com.janet.myrule
④ 上面包下新建 MySelfRule 规则类:
package com.janet.myrule;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author Janet
* @date 2020/5/5
*
* 自定义负载均衡路由规则类
*/
@Configuration
public class MySelfRule {
@Bean
public IRule myRule(){
return new RandomRule(); //定义为随机
}
}
⑤ 主启动类添加 @RibbonClient
@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE", configuration = MySelfRule.class)
public class OrderMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderMain80.class, args);
}
}
⑥ 测试:http://localhost/consumer/payment/get/1
4. Ribbon负载均衡算法
4.1 原理
4.2 源码
public Server choose(ILoadBalancer lb, Object key) {
if (lb == null) {
log.warn("no load balancer");
return null;
}
Server server = null;
int count = 0;
while (server == null && count++ < 10) {
List<Server> reachableServers = lb.getReachableServers();
List<Server> allServers = lb.getAllServers();
int upCount = reachableServers.size();
int serverCount = allServers.size();
if ((upCount == 0) || (serverCount == 0)) {
log.warn("No up servers available from load balancer: " + lb);
return null;
}
int nextServerIndex = incrementAndGetModulo(serverCount);
server = allServers.get(nextServerIndex);
if (server == null) {
/* Transient. */
Thread.yield();
continue;
}
if (server.isAlive() && (server.isReadyToServe())) {
return (server);
}
// Next.
server = null;
}
if (count >= 10) {
log.warn("No available alive servers after 10 tries from load balancer: "
+ lb);
}
return server;
}
/**
* Inspired by the implementation of {@link AtomicInteger#incrementAndGet()}.
*
* @param modulo The modulo to bound the value of the counter.
* @return The next value.
*/
private int incrementAndGetModulo(int modulo) {
for (;;) {
int current = nextServerCyclicCounter.get();
int next = (current + 1) % modulo;
if (nextServerCyclicCounter.compareAndSet(current, next))
return next;
}
}
(CAS 、自旋锁)
4.3 手写本地负载均衡器
① 7001 / 7002 集群启动
② 8001 / 8002集群启动
在 8001 和 8002 两个 controller 中添加方法:
@GetMapping(value = "/payment/lb")
public String getPaymentLB() {
return serverPort;
}
③ 80 订单微服务改造
a)ApplicationContextBean 去掉注解 @LoadBalanced
b)新建 LoadBalancer 接口
package com.janet.springcloud.lb;
import org.springframework.cloud.client.ServiceInstance;
import java.util.List;
/**
* @author Janet
* @date 2020/5/5
*
* 手写 Ribbon 轮询接口类
*/
public interface LoadBalancer {
// 收集现在服务器集群上总共有多少台提供服务的机器
ServiceInstance instances(List<ServiceInstance> serviceInstances);
}
c)新建 MyLB 类
package com.janet.springcloud.lb;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author Janet
* @date 2020/5/5
*
* 手写 Ribbon 轮询实现类
*/
@Component
public class MyLB implements LoadBalancer {
private AtomicInteger atomicInteger = new AtomicInteger(0);
//获取 rest 接口第几次请求数
public final int getAndIncrement(){
int current;
int next; //代表是第几次访问
do {
// 第一次current 等于当前的初始值0
current = this.atomicInteger.get();
next = current >= 2147483647 ? 0 : current + 1;
// current 是期望值,next 是修改值.this.atomicInteger.compareAndSet(current,next) 表示当前值与期望值一样,
// 就修改,返回 true。那整体就返回 false,跳出循环。如果不行,就一直自旋,直到取到要要的值
}while (!this.atomicInteger.compareAndSet(current,next));
System.out.println("-----第几次访问------次数:next:"+next);
return next;
}
@Override
public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
//getAndIncrement()代表第几次访问,serviceInstances.size() 代表集群数量
int index = getAndIncrement() % serviceInstances.size();
return serviceInstances.get(index);
}
}
d)OrderController
重点是添加了 getPaymentLB 方法:
package com.janet.springcloud.controller;
import com.janet.springcloud.entities.CommonResult;
import com.janet.springcloud.entities.Payment;
import com.janet.springcloud.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.net.URI;
import java.util.List;
/**
* @author Janet
* @date 2020/4/29
*/
@RestController
@Slf4j
public class OrderController {
// private final static String PAYMENT_URL = "http://localhost:8001"; //暂时写死,后面再改
private final static String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE"; //这里写微服务注册的名称
//引入手写 Ribbon 轮询接口类
@Autowired
private LoadBalancer loadBalancer;
@Autowired
private DiscoveryClient discoveryClient;
@Autowired
private RestTemplate restTemplate;
@GetMapping("/consumer/payment/create") //只能发 get 请求
public CommonResult<Payment> create(Payment payment) {
return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
}
@GetMapping("/consumer/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
}
@GetMapping("/consumer/payment/getForEntity/{id}")
public CommonResult<Payment> getPaymentById2(@PathVariable("id") Long id) {
ResponseEntity<CommonResult> forEntity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
if(forEntity.getStatusCode().is2xxSuccessful())
return forEntity.getBody();
else
return new CommonResult<>(444,"操作失败");
}
@GetMapping(value = "/consumer/payment/lb")
public String getPaymentLB(){
List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
if(instances == null || instances.size() <= 0)
return null;
ServiceInstance instanceInstance = loadBalancer.instances(instances);
URI uri = instanceInstance.getUri();
return restTemplate.getForObject(uri + "/payment/lb",String.class);
}
}
e)测试:http://localhost/consumer/payment/lb