目录
- 一、Ribbon负载均衡服务调用
- 概述
- Ribbon负载均衡演示
- RestTemplate
- Ribbon核心组件IRule
- Ribbon负载均衡算法
- 原理(RoundRobinRule原理)
- 源码(RoundRobinRule)
- 手写负载算法
- 二、OpenFeign服务接口调用
- 概述
- 使用步骤
- OpenFeign超时控制
- OpenFeign日志打印功能
一、Ribbon负载均衡服务调用
概述
Ribbon负载均衡演示
Ribbon是客户端(消费者)负载均衡的工具。
Ribbon的POM
代码语言:javascript复制 <!--Ribbon的依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
升级最新版本,eureka自带Ribbon的依赖
RestTemplate
@LoadBalanced注解给RestTemplate开启负载均衡的能力。
官方文档:https://docs.spring.io/spring-framework/docs/5.2.2.RELEASE/javadoc-api/org/springframework/web/client/RestTemplate.html
getForObject/getForEntity方法
测试getForEntity方法
代码语言:javascript复制 @GetMapping("/consumer/payment/getForEntity/{id}")
public CommonResult<Payment> getPayment2(@PathVariable("id") Long id){
ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL "/payment/get/" id, CommonResult.class);
if (entity.getStatusCode().is2xxSuccessful()){
return entity.getBody();
}else {
return new CommonResult<>(444,"操作失败");
}
}
重启测试
Ribbon核心组件IRule
IRule:根据特定的算法从服务列表中选取一个要访问的服务。 IRule接口的实现:
负载均衡常用规则:默认为RoundRobinRule轮询。
替换规则
Ribbon的自定义配置类不可以放在@ComponentScan所扫描的当前包下以及子包下,否则这个自定义配置类就会被所有的Ribbon客户端共享,达不到为指定的Ribbon定制配置,而@SpringBootApplication注解里就有@ComponentScan注解,所以不可以放在主启动类所在的包下。(因为Ribbon是客户端(消费者)这边的,所以Ribbon的自定义配置类是在客户端(消费者)添加,不需要在提供者或注册中心添加)
- 重新创建项目包
- 创建MySelfRule规则类
@Configuration
public class MySelfRule {
@Bean
public IRule myRule(){
// 随机
return new RandomRule();
}
}
- 主启动添加
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE", configuration = MySelfRule.class)
,告诉服务用那种负载模式
@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE", configuration = MySelfRule.class)
public class OrderMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderMain80.class);
}
}
- 启动测试,浏览器输入
http://localhost/consumer/payment/get/1
,多次刷新实现负载均衡为随机。
Ribbon负载均衡算法
原理(RoundRobinRule原理)
源码(RoundRobinRule)
代码语言:javascript复制 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;
}
}
手写负载算法
- 启动7001、7002 eureka集群
- 修改8001、8002的controller
@GetMapping(value = "/payment/lb")
public String getPaymentLB(){
return serverPort;
}
3.80订单微服务改造
- 去掉ApplicationContextConfig里restTemplate方法上的@LoadBalanced注解。
- 在springcloud包下新建lb.ILoadBalancer接口(自定义负载均衡机制(面向接口))
public interface ILoadBalancer {
//传入具体实例的集合,返回选中的实例
ServiceInstance instance(List<ServiceInstance> serviceInstances);
}
- 在lb包下新建自定义ILoadBalancer接口的实现类
@Component
public class MyLB implements LoadBalancer {
private AtomicInteger atomicInteger = new AtomicInteger(0);
public 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);
return next;
}
@Override
public ServiceInstance instance(List<ServiceInstance> serviceInstances) {
int index = getAndIncrement() % serviceInstances.size();
return serviceInstances.get(index);
}
}
- 修改controller
@Resource
private RestTemplate restTemplate;
@Resource
private LoadBalancer loadBalancer;
@GetMapping("/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.instance(instances);
URI uri = serviceInstance.getUri();
return restTemplate.getForObject(uri "/payment/lb",String.class);
}
二、OpenFeign服务接口调用
概述
官网文档:https://cloud.spring.io/spring-cloud-static/Hoxton.SR1/reference/htmlsingle/#spring-cloud-openfeign
Feign是一个声明式的web服务客户端,让编写web服务客户端变得非常容易,只需创建一个接口并在接口上添加注解即可。
OpenFeign和Feign的区别
OpenFeign使用在客户端(消费测)
使用步骤
- 新建模块
- 改POM
<dependencies>
<!-- openfeign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- eureka-client -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- 引用自己定义的api通用包,可以使用Payment支付Entity -->
<dependency>
<groupId>com.zhao.springcloud</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>
- 写YML
server:
port: 80
eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka,http://eureka7003.com:7003/eureka
- 主启动类
@SpringBootApplication
// 激活开启feign
@EnableFeignClients
public class OrderFeign {
public static void main(String[] args) {
SpringApplication.run(OrderFeign.class);
}
}
- 业务类
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {
@GetMapping("/payment/get/{id}")
public CommonResult getPaymentById(@PathVariable("id") Long id);
}
- 编写controller
@RestController
@Slf4j
public class OrderFeignController {
@Resource
private PaymentFeignService paymentFeignService;
@GetMapping("/consumer/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
return paymentFeignService.getPaymentById(id);
}
}
7.启动测试 自带负载均衡功能
OpenFeign超时控制
提供者在处理服务时用了3秒,提供者认为花3秒是正常,而消费者只愿意等1秒,1秒后,提供者会没返回数据,消费者就会造成超时调用报错。所以需要双方约定好时间,不使用默认的。
模拟超时出错的情况
- 在8001的PaymentController里添加:(模拟服务处理时间长)
@GetMapping("/payment/feign/timeout")
public String paymentFeignTimeout(){
try{
TimeUnit.SECONDS.sleep(3);
}catch (InterruptedException e){
e.printStackTrace();
}
return serverPort;
}
- 在80的PaymentFeignService中添加:
@GetMapping("/payment/feign/timeout")
public String paymentFeignTimeout();
- 然后在80的OrderFeignController中添加:
@GetMapping("/consumer/payment/feign/timeout")
public String paymentFeignTimeout(){
//openFeign-ribbon,客户端一般默认等待1秒
return paymentFeignService.paymentFeignTimeout();
}
- 测试
- YML开启超时时间
#没提示不管它,可以设置
ribbon:
#指的是建立连接后从服务器读取到可用资源所用的时间
ReadTimeout: 5000
#指的是建立连接使用的时间,适用于网络状况正常的情况下,两端连接所用的时间
ConnectTimeout: 5000
- 重新测试
OpenFeign日志打印功能
概述
打印级别
设置步骤
- 配置日志bean
@Configuration
public class FeignConfig {
@Bean
Logger.Level feignLogLevel(){
return Logger.Level.FULL;
}
}
- Yml中开启日志
logging:
level:
#feign日志以什么级别监控哪个接口
com.zhao.springcloud.service.PaymentFeignService: debug
- 测试
我的博客即将同步至腾讯云开发者社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=9pjswi3oo5to