当前位置: 首页 > news >正文

(第五篇)spring cloud之Ribbon负载均衡

目录

一、介绍

1、介绍

2、本地负载和服务器负载

3、RestTemplate的使用

二、核心组件IRule

1、介绍

2、修改cloud-consumer-order80工程

三、自定义负载均衡算法

1、原理

 2、自定义算法


一、介绍

1、介绍

Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端负载均衡的工具。Ribbon是Netflix发布的开源项目,主要功能是提供客户端的软件负载均衡算法和服务调用。Ribbon客户端组件提供一系列完善的配置项如连接超时,重试等;Ribbon目前也进入维护模式。

2、本地负载和服务器负载

         Nginx是服务器负载均衡,客户端所有请求都会交给nginx,然后由nginx实现转发请求。负载均衡是由服务端实现的。
         Ribbon本地负载均衡,在调用微服务接口时候,会在注册中心上获取注册服务列表,之后缓存到JVM本地,从而在本地实现RPC远程服务调用技术。

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

3、RestTemplate的使用

        RestTemplate 是Spring框架提供的一个用于发起HTTP请求的同步客户端工具,它简化了与http服务的通信过程,并遵循RESTful原则。在Spring Boot项目中,可以通过注入RestTemplate来使用,或者进行一些简单的配置来满足特定需求。

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

一些get方法:

<T> T getForObject(String url, Class<T> responseType, Object... uriVariables);


<T> T getForObject(String url, Class<T> responseType, Map<String, ?> uriVariables);
 
<T> T getForObject(URI url, Class<T> responseType);
 
<T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object... uriVariables);
 
<T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String, ?> uriVariables);
 
<T> ResponseEntity<T> getForEntity(URI var1, Class<T> responseType);

一些post方法:

 <T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables);
 
<T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables);
 
<T> T postForObject(URI url, @Nullable Object request, Class<T> responseType);
 
<T> ResponseEntity<T> postForEntity(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables);
 
<T> ResponseEntity<T> postForEntity(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables);
 
<T> ResponseEntity<T> postForEntity(URI url, @Nullable Object request, Class<T> responseType);

例如:简单配置

@Configuration
public class RestTemplateConfig {@Beanpublic RestTemplate restTemplate(ClientHttpRequestFactory factory) {return new RestTemplate(factory);}@Beanpublic ClientHttpRequestFactory simpleClientHttpRequestFactory() {SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();factory.setReadTimeout(15000); // 设置读取超时时间factory.setConnectTimeout(15000); // 设置连接超时时间return factory;}
}

Get使用:

// 发起GET请求并将响应映射到TempUser对象
TempUser result = restTemplate.getForObject("http://localhost:8080/getUser?userName=张三&age=18", TempUser.class);// 使用参数映射
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("userName", "张三");
paramMap.put("age", 18);
TempUser result = restTemplate.getForObject("http://localhost:8080/getUser?userName={userName}&age={age}", TempUser.class, paramMap);

Post使用:

// 发起POST请求并获取响应
TempUser param = new TempUser();
param.setUserName("张三");
param.setAge(18);
TempUser result = restTemplate.postForObject("http://localhost:8080/getPostUser", param, TempUser.class);// 发送带有请求头的POST请求
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<TempUser> httpEntity = new HttpEntity<>(param, headers);
TempUser result = restTemplate.postForObject("http://localhost:8080/getPostUser", httpEntity, TempUser.class);

二、核心组件IRule

1、介绍

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

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

2、修改cloud-consumer-order80工程

(1)注意点

官方文档明确给出了警告:这个自定义配置类不能放在@ComponentScan所扫描的当前包下以及子包下,否则我们自定义的这个配置类就会被所有的Ribbon客户端所共享,达不到特殊化定制的目的了

(2)新建MySelfRule

package com.hk.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
{@Beanpublic IRule myRule(){return new RandomRule();//定义为随机}
}

(3)修改启动类

package com.hk.cloudstudy;import com.hk.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 MainApp80 {public static void main(String[] args) {SpringApplication.run(MainApp80.class,args);}
}

(4)测试

启动7001,8001和8002,在启动80

访问GET http://localhost:80/consumer/payment/get/1

发现打印的端口是随机出现的

三、自定义负载均衡算法

1、原理

 负载均衡算法:rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标  ,每次服务重启动后rest接口计数从1开始。
 List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
如:   List [0] instances = 127.0.0.1:8002
   List [1] instances = 127.0.0.1:8001
 
8001+ 8002 组合成为集群,它们共计2台机器,集群总数为2, 按照轮询算法原理:
当总请求数为1时: 1 % 2 =1 对应下标位置为1 ,则获得服务地址为127.0.0.1:8001
当总请求数位2时: 2 % 2 =0 对应下标位置为0 ,则获得服务地址为127.0.0.1:8002
当总请求数位3时: 3 % 2 =1 对应下标位置为1 ,则获得服务地址为127.0.0.1:8001
当总请求数位4时: 4 % 2 =0 对应下标位置为0 ,则获得服务地址为127.0.0.1:8002
如此类推......


 2、自定义算法

(1)修改80服务,

ApplicationContextBean去掉注解@LoadBalanced
 

package com.hk.cloudstudy.config;import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;@Configuration
public class ApplicationContextConfig {//使用@LoadBalanced注解赋予RestTemplate负载均衡的能力@Bean
//    @LoadBalancedpublic RestTemplate restTemplate(){return new RestTemplate();}
}


 (2)创建LoadBalancer接口

package com.hk.cloudstudy.mylb;import org.springframework.cloud.client.ServiceInstance;import java.util.List;public interface LoadBalancer {ServiceInstance instances(List<ServiceInstance> serviceInstances);
}

 (3)创建接口的实现

package com.hk.cloudstudy.mylb;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);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));return next;}@Overridepublic ServiceInstance instances(List<ServiceInstance> serviceInstances) {// rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标int index = getAndIncrement() % serviceInstances.size();return serviceInstances.get(index);}
}

(4)修改controller


 

package com.hk.cloudstudy.controller;import com.hk.cloudstudy.entities.CommonResult;
import com.hk.cloudstudy.entities.Payment;
import com.hk.cloudstudy.mylb.LoadBalancer;
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.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;import java.net.URI;
import java.util.List;@RestController
public class OrderController {//    public static final String PAYMENT_URL = "http://localhost:8001";public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE"; // CLOUD-PAYMENT-SERVICE注册中心的服务名称@Autowiredprivate RestTemplate restTemplate;//可以获取注册中心上的服务列表@Autowiredprivate DiscoveryClient discoveryClient;@Autowiredprivate LoadBalancer loadBalancer;@GetMapping("/consumer/payment/{id}")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);}//客户端用浏览器是get请求,但是底层实质发送post调用服务端8001@GetMapping("/consumer/payment/create")public CommonResult create(Payment payment){return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);}@GetMapping("/consumer/payment/get/{id}")public CommonResult getPaymentById(@PathVariable("id") Long id){return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class, id);}}

(5)8001和8002修改controller

    @GetMapping(value = "/payment/lb")public String getPaymentLB(){return serverPort;}

(6)测试

启动7001,8001和8002, 启动80

访问:http://localhost/consumer/payment/lb

发现8001和8002交替出现
 

http://www.dtcms.com/a/338827.html

相关文章:

  • 主流 3D 模型格式(FBX/OBJ/DAE/GLTF)材质支持与转换操作指南
  • 云存储的高效安全助手:阿里云国际站 OSS
  • ICCV 2025 | 首个3D动作游戏专用VLA模型,打黑神话只狼超越人类玩家
  • iOS 性能监控实践,如何构建从开发到运维的持续优化体系
  • 面试题储备-MQ篇 3-说说你对Kafka的理解
  • 如何用给各种IDE配置R语言环境
  • Halcon联合C# 添加工具类让winform自动根据窗体大小自适应缩放所有控件
  • 知行社黄剑杰:金融跨界,重塑震区救援新章
  • 《基于大数据的全球用水量数据可视化分析系统》用Python+Django开发,为什么导师却推荐用Java+Spring Boot?真相揭秘……
  • sqli-labs通关笔记-第55关 GET数值型注入(括号闭合 限制14次探测机会)
  • 今日行情明日机会——20250819
  • 20.2 QLoRA微调全局参数实战:高点击率配置模板+显存节省50%技巧
  • Linux下Nginx安装及负载均衡配置
  • Python 3.14深度解析:革命性特性与性能优化实践
  • Go高效复用对象:sync.Pool详解
  • Windows内核开发笔记
  • 免费导航规划API接口详解:调用指南与实战示例
  • 一个基于前端技术的小狗寿命阶段计算网站,帮助用户了解狗狗在不同年龄阶段的特点和需求。
  • 数据链路层-网络层-传输层
  • js 值转换boolean方式
  • AutoSAR实战:DCM配置之Response On Event (0x86)事件响应配置指导
  • 【深度学习计算性能】06:多GPU的简洁实现
  • 守护通行安全,“AI+虚拟仿真”领航交通设施人才培育
  • ROS点云可视化工具——Foxglove工具使用
  • Spring Cloud 微服务架构:Eureka 与 ZooKeeper 服务发现原理与实战指南 NO.1
  • 前端如何处理首屏优化问题
  • 微信小程序实现蓝牙开启自动播放BGM
  • 八大排序简介
  • 【集合框架LinkedList底层添加元素机制】
  • el-table 动态列表渲染和动态表格背景设置