博客学习参考视频

一、Ribbon 负载均衡服务调用

① 概述

1.是什么

image-20201011221103800

2.官网资料

https://github.com/Netflix/ribbon/wiki/Getting-Started

Ribbon 目前也进入维护模式

image-20201011222107889

未来替换方案

image-20201011222224992

3.能干嘛

  • LB(负载均衡) : 集中式 LB、 进程内 LB ,前面我们写过了 80 通过轮询负载访问 8001/8002
  • 一句话: 负载均衡+RestTemplate 调用

② Ribbon 负载均衡演示

1.架构说明

image-20201011222519604

image-20201011223037582

总结: Ribbon 其实就是一个软负载均衡的客户端组件,他可以和其他所需请求的客户端结合使用,和 eureka 结合只是其中的一个实例。

2.POM

image-20201011223304791

image-20201011223320127

3.RestTemplate 的使用

官网:https://docs.spring.io/spring-framework/docs/5.2.2.RELEASE/javadoc-api/org/springframework/web/client/RestTemplate.html

image-20201011223821711

getForObject 方法/getForEntity 方法

image-20201011223916541

postForObject/postForEntity

image-20201012214733664

③ Ribbon 核心组件 IRule

1.IRule

根据特定算法从服务列表中选取一个要访问的服务

image-20201012215033018

  • com.netflix.loadbalancer.RoundRobinRule 轮询
  • com.netflix.loadbalancer.RandomRule 随机
  • com.netflix.loadbalancer.RetryRule: 先按照 RoundRobinRule 的策略获取服务, 如果获取服务失败则在指定时间内会进行重试
  • WeightedResponseTimeRule : 对 RoundRobinRule 的扩展, 响应速度越快的实例选择权重越大, 越容易被选择
  • BestAvailableRule : 会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务, 然后选择一个并发量最小的服务
  • AvailabilityFilteringRule : 先过滤掉故障实例, 再选择并发较小的实例
  • ZoneAvoidanceRule: 默认规则, 复合判断 server 所在区域的性能和 server 的可用性选择服务器

2.如何替换

修改 cloud-consumer-order80

注意配置细节

image-20201012220109661

image-20201012220120906

新建 package: com.oy.myrule

image-20201012220421960

主启动类添加@RibbonClient

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import com.oy.myrule.MySelfRule;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.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

image-20201012221336131

④ Ribbon 负载均衡算法

1.原理

image-20201012221459557

2.RoundRobinRule 源码

3.手写

7001/7002 集群启动

8001/8002 微服务改造

Controller:

1
2
3
4
@GetMapping(value = "/payment/lib")
public String getPaymentLB(){
return serverPort;
}

80 订单微服务改造

  • ApplicationContextBean 去掉@LoadBalanced

  • LoadBalancer 接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.oy.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class MyLB implements LoadBalancer{

private AtomicInteger atomicInteger = new AtomicInteger(0);

// 坐标
private final int getAndIncrement(){
int current;
int next;
do{
current = this.atomicInteger.get();
next = current >= 2147483647 ? 0 : current+1;
}while (!this.atomicInteger.compareAndSet(current,next)); // 第一个参数是期望值,第二个参数是修改值是
System.out.println("******第几次访问,次数next:" + next + ",current:"+ current);
return next;
}

@Override
public ServiceInstance instances(List<ServiceInstance> serviceInstances) {// 得到机器列表

// 获取服务器的下标位置
int index = getAndIncrement() % serviceInstances.size();
return serviceInstances.get(index);
}
}

image-20201013233506386

  • OrderController
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* @Author OY
* @Date 2020/10/7
*/

@RestController
public class OrderController {

@Resource
private RestTemplate restTemplate;

@Resource
LoadBalancer loadBalancer;


@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 serviceInstance = loadBalancer.instances(instances);
URI uri = serviceInstance.getUri();
return restTemplate.getForObject(uri+"/payment/lb",String.class);

}

}

_效果_:

image-20201013233900529

image-20201013233917559

二、OpenFeign 服务接口调用

① 概述

1.OpenFeign 是什么

image-20201015224448756

image-20201015224506884 Feign 是一个声明式的 web 服务客户端,让编写 web 服务客户端变得非常容易,只需要创建一个接口上添加注解即可

​ GitHub: https://github.com/spring-cloud/spring-cloud-openfeign

2.能干嘛

image-20201015224914584

3.Feign 和 OpenFeign 两者区别

image-20201015225119181

② OpenFeign 使用步骤

接口 + 注解: 微服务调用接口 + @FeignClient

新建 cloud-consumer-feign-order80

Feign 在消费端使用

image-20201015225711299

POM

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>clould</artifactId>
<groupId>com.oy</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>cloud-consumer-feign-order80</artifactId>

<!--openfeign-->
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency>
<dependency>
<groupId>com.oy</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency><groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

YML

1
2
3
4
5
6
7
server:
port: 80
eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka

主启动类 : @ EnableFeignClients

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

业务类

  • 业务逻辑接口 + @FeignClient 配置调用 provider 服务
  • 新建 PaymentFeignService 接口并新增注解 @FeignClient
1
2
3
4
5
6
7
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {

@GetMapping(value = "/payment/get/{id}")
public CommonResult getPaymentById(@PathVariable("id") Long id);
}

Controller

1
2
3
4
5
6
7
8
9
10
11
12
@RestController
public class OrderFeignController {

@Resource
private PaymentFeignService paymentFeignService;

@GetMapping(value = "/consumer/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id")Long id){
return paymentFeignService.getPaymentById(id);

}
}

测试

image-20201015233219044

小总结

image-20201015233350231

③ OpenFeign 超时控制

1.超时设置,故意设置超时演示出错情况

服务提供方 8001 故意写暂停程序

1
2
3
4
5
6
7
8
9
10
@GetMapping(value = "/payment/feign/timeout")
public String paymentFeignTimeOut(){
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}

return serverPort;
}

​ 服务消费方 80 添加超时方法 PaymentFeignService

1
2
3
4
5
6
7
8
9
10
11
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {

// 添加超时方法 PaymentFeignService
@GetMapping(value = "/payment/feign/timeout")
public String paymentFeignTimeOut();

@GetMapping(value = "/payment/get/{id}")
public CommonResult getPaymentById(@PathVariable("id") Long id);
}

​ 服务消费方 80 添加超时方法 OrderFeignController

1
2
3
4
@GetMapping(value = "/consumer/payment/feign/timeout")
public String paymentFeignTimeOut(){
return paymentFeignService.paymentFeignTimeOut();
}

测试:

  • 错误页面

image-20201015235756416

2.OpenFeign 默认等待一秒钟, 超过后报错

3.是什么

​ 默认 Feign 客户端等待一秒,但是服务器处理需要超过 1 秒钟,导致 Feign 客户端不想等待了,直接返回报错。为了避免这样的情况,有时候我们需要设置 Feign 客户端的超时控制。

在 yml 文件中开启配置

image-20201016000801551

4.YML 文件里需要开启 OpenFeign 客户端超时控制

1
2
3
4
5
6
7
8
9
10
11
12
13
server:
port: 80
eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
# 设置feign客户端超时时间(OpenFeign默认支持ribbon)
ribbon:
# 指的是建立连接所用的时间,适用于网络状态正常的情况下,两端连接所用的时间
ReadTimeout: 5000
# 指的是建立连接后从服务器读取到可用资源所用的时间
ConnectTimeout: 5000

测试:

http://localhost/consumer/payment/feign/timeout

image-20201016001017944

④ OpenFeign 日志打印功能

1.日志打印功能

2.是什么

image-20201016001419333

3.日志级别

image-20201016001452126

4.配置日志 bean

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.oy.springcloud;


import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
* @Author OY
* @Date 2020/10/16
*/

@Configuration
public class FeignConfig {

@Bean
Logger.Level feignLoggerLevel(){
return Logger.Level.FULL;
}
}

5.YML 文件里面需要开启日志的 Feign 客户端

1
2
3
logging:
level:
com.oy.springcloud.service.PaymentFeignService: debug

image-20201016002246618

6.后台日志查看

image-20201016002353716