SpringCloud Hoxton版 + SpringCloud alibaba学习笔记(3)-- Ribbon负载均衡服务调用

151 阅读1分钟

上一篇:SpringCloud Hoxton版 + SpringCloud alibaba学习笔记(2)-- 服务注册与发现

一、Ribbon负载均衡服务调用

1、概述

①、是什么

在这里插入图片描述

②、官网资料

github.com/Netflix/rib… Ribbon目前也进入维护模式 在这里插入图片描述 未来替换方案 在这里插入图片描述

③、能干嘛

LB(负载均衡) 在这里插入图片描述 集中式LB 在这里插入图片描述 进程内LB 在这里插入图片描述 前面我们讲解过了80通过轮询负载访问8001/8002 一句话:负载均衡+RestTemplate调用

2、Ribbon负载均衡演示

①、架构说明

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

②、pom

在这里插入图片描述 在这里插入图片描述

③、二说RestTemplate的使用

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

在这里插入图片描述 getForObject方法/getForEntity方法 在这里插入图片描述 postForObject/postForEntity 在这里插入图片描述 GET请求方法 POST请求方法

3、Ribbon核心组件IRule

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

在这里插入图片描述

在这里插入图片描述

②、如何替换

1)、修改cloud-consumer-order80 2)、注意配置细节、 在这里插入图片描述 3)、新建package(com.atguigu.myrule) 在这里插入图片描述 4)、上面包下新建MySelfRule规则类

package com.atguigu.myrule;

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MySelfRule {

    @Bean
    public IRule myRule(){
        return new RandomRule();//定义为随机
    }
}

5)、主启动类添加@RibbonClient

package com.atguigu.springcloud;

import com.atguigu.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;


@EnableEurekaClient
@SpringBootApplication
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration = MySelfRule.class)
public class OrderMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderMain80.class,args);
    }

}

6)、测试 http://localhost/consumer/payment/get/31

4、Ribbon负载均衡算法

①、原理

在这里插入图片描述

②、RoundRobinRule源码
③、自己试着写一个本地负载均衡器试试

下一篇:SpringCloud Hoxton版 + SpringCloud alibaba学习笔记(4)-- OpenFeign服务接口调用