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

spring cloud之ribbon复习回顾

其实在项目中直接使用ribbon时不多,大多是使用feign的,其实feign底层也是通过ribbon构建的,主要记忆一下计算规则,ribbon的源码还是很不错的,还是值得学习的。

1、添加pom

<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>

2、启动类注解

我没有在启动类添加注解,直接另外一个配置类@Configuration添加

3、添加配置

# 默认是轮训,都有随机、加权响应时间、重试,看具体业务和服务器搭配
#eureka-client.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RoundRobinRule

4、参照源码规则,自己编写规则

这里是通过hashcode在hash闭环定义的,当每台服务器hashcode在hash闭环的对应位置后,每次请求直接定位到hash中顺时针寻找最近的服务器

package com.xl.ribbon.consumer.rules;import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.Server;
import lombok.NoArgsConstructor;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.condition.RequestConditionHolder;import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;@NoArgsConstructor
public class MyRule extends AbstractLoadBalancerRule implements IRule {@Overridepublic void initWithNiwsConfig(IClientConfig iClientConfig) {}@Overridepublic Server choose(Object key) {HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();String uri = request.getServletPath() + "?" + request.getQueryString();return route(uri.hashCode(), getLoadBalancer().getAllServers());}public Server route(int hashId, List<Server> servers) {if (CollectionUtils.isEmpty(servers)) {return null;}TreeMap<Long, Server> serverMap = new TreeMap<>();servers.forEach(server -> {// 虚化若干个服务节点,到环上for (int i = 0; i < 8; i++) {long hash = hash(server.getId() + i);serverMap.put(hash, server);}});long hash = hash(String.valueOf(hashId));SortedMap<Long, Server> last = serverMap.tailMap(hash);// 当request URL的hash值大于任意一个服务器对应的hashKey,// 取serverMap中的第一个节点if (last.isEmpty()) {Server value = serverMap.firstEntry().getValue();last.put(hash, value);}return last.get(last.firstKey());}public long hash(String key) {MessageDigest md5;try {md5 = MessageDigest.getInstance("MD5");} catch (NoSuchAlgorithmException e) {throw new RuntimeException(e);}byte[] keyBytes = null;try {keyBytes = key.getBytes("UTF-8");} catch (UnsupportedEncodingException e) {throw new RuntimeException(e);}md5.update(keyBytes);byte[] digest = md5.digest();long hash = (digest[2] & 0xFF << 16) | (digest[1] & 0xFF) << 8 | (digest[0] & 0xFF);return hash & 0xffffffffL;}
}

5、规则配置

其实直接配置在application.properties也可以,这里我是在一个配置文件

package com.xl.ribbon.consumer;import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import com.xl.ribbon.consumer.rules.MyRule;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** Created by lig on 2024/10/12.*/
@Configuration
//@RibbonClient(name = "eureka-client", configuration = com.netflix.loadbalancer.RandomRule.class)
@RibbonClient(name = "eureka-client", configuration = MyRule.class)
public class RibbonConfiguration {
//
//    @Bean
//    public IRule defaultLBStrategy() {
//        return new RandomRule();
//    }}

6、接口

package com.xl.ribbon.consumer;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;/*** Created by lig on 2024/10/12.*/
@RestController
public class RibbonController {@Autowiredprivate RestTemplate restTemplate;@GetMapping("/sayHi")public String sayHi() {return restTemplate.getForObject("http://eureka-client/sayHi", String.class);}}

总结

其实在实际项目中ribbon编写符合自己业务的规则还是挺复杂的,用途还是挺广的.

http://www.lryc.cn/news/499714.html

相关文章:

  • RFT 强化微调
  • SpringBoot教程(三十二) SpringBoot集成Skywalking链路跟踪
  • 分布式搜索引擎Elasticsearch
  • 在Vue.js中生成二维码(将指定的url+参数 生成二维码)
  • 统信桌面专业版部署postgresql-14.2+postgis-3.2方法介绍
  • 数字图像处理(16):RGB与HSV互转
  • web组态可视化编辑器
  • 数组 - 八皇后 - 困难
  • 【分布式】Redis分布式缓存
  • Ubuntu——extrepo添加部分外部软件源
  • 评估大语言模型(LLM)在分子预测任务能够理解分子几何形状性能
  • 如何查看电脑刷新率
  • mysql集群MHA方式部署
  • 第十七章 使用 MariaDB 数据库管理系统
  • rabbitmq 安装延时队列插件rabbitmq_delayer_message_exchange(linux centOS 7)
  • Unity性能优化---动态网格组合(一)
  • Appium:安装uiautomator2失败
  • 电子信息工程自动化 单片机彩灯控制
  • word poi-tl 表格功能增强,实现表格功能垂直合并
  • LSTM-CNN-BP-RF-SVM五模型咖喱融合策略混合预测模型
  • 《鸿蒙开发-答案之书》 怎么设置Json字段的别名
  • ftp服务器搭建-安装、配置及验证
  • 鸿蒙应用获取wifi连接的ip地址(官方文档获取的格式转换成192.168.1.xxx格式)
  • c++数据结构算法复习基础--11--高级排序算法-快速排序-归并排序-堆排序
  • 人工智能学习路线详细规划
  • 深度学习之视觉处理
  • 遇到问题:hive中的数据库和sparksql 操作的数据库不是同一个。
  • Spring Boot与Spring Security集成:前后分离认证流程的优化实践
  • 设计模式——Chain(责任链)设计模式
  • HarmonyOS(63) ArkUI 自定义占位组件NodeContainer