数据库拆分4--使用sharding-jdbc来实现水平拆分

news2024/9/22 23:18:41

有三张表 user log order表,先将user log 和order垂直分库,然后将user表水平拆分

配置文件

spring.shardingsphere.enabled=true

spring.shardingsphere.datasource.names=wim-user,wim-order

spring.shardingsphere.datasource.wim-user.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.wim-user.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.wim-user.url=jdbc:mysql://127.0.0.1:3306/wim-user?serverTimezone=UTC&useSSL=false
spring.shardingsphere.datasource.wim-user.username=root
spring.shardingsphere.datasource.wim-user.password=123456

spring.shardingsphere.datasource.wim-order.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.wim-order.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.wim-order.url=jdbc:mysql://127.0.0.1:3306/wim-order?serverTimezone=UTC&useSSL=false
spring.shardingsphere.datasource.wim-order.username=root
spring.shardingsphere.datasource.wim-order.password=123456

spring.shardingsphere.sharding.tables.user_t.actual-data-nodes=wim-user.user_t_$->{0..1}
spring.shardingsphere.sharding.tables.log_t.actual-data-nodes=wim-user.log_t

spring.shardingsphere.sharding.tables.user_t.table-strategy.inline.sharding-column=user_id
spring.shardingsphere.sharding.tables.user_t.table-strategy.inline.algorithm-expression=user_t_$->{user_id % 2}

spring.shardingsphere.sharding.tables.log_t.table-strategy.inline.sharding-column=id
spring.shardingsphere.sharding.tables.log_t.table-strategy.inline.algorithm-expression=log_t


spring.shardingsphere.sharding.default-data-source-name=wim-order

spring.shardingsphere.props.sql.show=true

拆分的配置方法 直接看一下对应代码和实现类

学习一下各种分片策略:

行表达式分片策略(InlineShardingStrategy)

YamlInlineShardingStrategyConfiguration
public final class YamlInlineShardingStrategyConfiguration implements YamlBaseShardingStrategyConfiguration {
    private String shardingColumn;
    private String algorithmExpression;

    public YamlInlineShardingStrategyConfiguration() {
    }

    @Generated
    public String getShardingColumn() {
        return this.shardingColumn;
    }

    @Generated
    public String getAlgorithmExpression() {
        return this.algorithmExpression;
    }

    @Generated
    public void setShardingColumn(String shardingColumn) {
        this.shardingColumn = shardingColumn;
    }

    @Generated
    public void setAlgorithmExpression(String algorithmExpression) {
        this.algorithmExpression = algorithmExpression;
    }
}
spring.shardingsphere.sharding.tables.user_t.actual-data-nodes=wim-user.user_t_$->{0..1}
spring.shardingsphere.sharding.tables.user_t.table-strategy.inline.sharding-column=user_id
spring.shardingsphere.sharding.tables.user_t.table-strategy.inline.algorithm-expression=user_t_$->{user_id % 2}

需要配置分片键和分片表达式

有两张user表  user_t_0 user_t_1 根据user_id%2来路由到不同数据库。

1)使用场景:只支持单分片健;支持对 SQL语句中的 = 、IN 等的分片操作,不支持between and。

2)使用方法:适用于做简单的分片算法,在配置中使用 Groovy 表达式,无需自定义分片算法,省去了繁琐的代码开发,是几种分片策略中最为简单的。

标准分片策略(StandardShardingStrategy)

YamlStandardShardingStrategyConfiguration
public final class YamlStandardShardingStrategyConfiguration implements YamlBaseShardingStrategyConfiguration {
    private String shardingColumn;
    private String preciseAlgorithmClassName;
    private String rangeAlgorithmClassName;

SQL 语句中有>>=<=<=,IN和BETWEEN AND操作符,都可以应用此分片策略。它只支持对单个分片健(字段)为依据的分库分表,并提供了两种分片算法 PreciseShardingAlgorithm(精准分片)和 RangeShardingAlgorithm(范围分片)

精准分库算法:实现 PreciseShardingAlgorithm 接口,并重写 doSharding() 方法。其中 Collection<String> 参数在几种分片策略中使用一致,在分库时值为所有分片库的集合 databaseNames,分表时为对应分片库中所有分片表的集合 tablesNames;PreciseShardingValue 为分片属性,其中 logicTableName 为逻辑表,columnName 分片健(字段),value 为从 SQL 中解析出的分片健的值;

假设log表需要根据id来分片 大于1000的分片0  其他分片1

spring.shardingsphere.sharding.tables.log_t.actual-data-nodes=wim-user.log_t_$->{0..1}
spring.shardingsphere.sharding.tables.log_t.table-strategy.standard.sharding-column=id
spring.shardingsphere.sharding.tables.log_t.table-strategy.standard.precise-algorithm-class-name=com.chen.algorithm.MyPreciseShardingAlgorithm
public class MyPreciseShardingAlgorithm implements PreciseShardingAlgorithm {
	
	@Override
	public String doSharding(Collection collection, PreciseShardingValue preciseShardingValue) {
		Object[] ds = collection.toArray();
		long logId = (long) preciseShardingValue.getValue();
		if (logId > 1000) {
			return (String) ds[0];
		} else {
			return (String) ds[1];
		}
	}
}

在doSharding方法中可以实现更加复杂的判断逻辑

范围分片算法:分片健字段用到 BETWEEN AND操作符会使用到此算法,会根据 SQL中给出的分片健值范围值处理分库、分表逻辑。自定义范围分片算法需实现 RangeShardingAlgorithm 接口,重写 doSharding() 方法,Collection<String> 在分库、分表时分别代表分片库名和表名集合,RangeShardingValue 这里取值方式稍有不同, lowerEndpoint 表示起始值, upperEndpoint 表示截止值

假设log表 当查询时间范围包含2021年时 则从两个数据库查询合并结果返回 否则取第一个数据库数据返回

spring.shardingsphere.sharding.tables.log_t.actual-data-nodes=wim-user.log_t_$->{0..1}
spring.shardingsphere.sharding.tables.log_t.table-strategy.standard.sharding-column=log_date
spring.shardingsphere.sharding.tables.log_t.table-strategy.standard.range-algorithm-class-name=com.chen.algorithm.MyRangeShardingAlgorithm
spring.shardingsphere.sharding.tables.log_t.table-strategy.standard.precise-algorithm-class-name=com.chen.algorithm.MyPreciseShardingAlgorithm
public class MyRangeShardingAlgorithm implements RangeShardingAlgorithm<Date> {
	
	@Override
	public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Date> rangeShardingValue) {
		Range range = rangeShardingValue.getValueRange();
		boolean flag = range.contains("2021");
		if (flag) {
			return collection;
		} else {
			return Arrays.asList((String) collection.toArray()[0]);
		}
	}
}
RangeShardingAlgorithm算法需要和PreciseShardingAlgorithm一同实现来使用 否则算法加载会报错 好奇怪的逻辑
 if (null != yamlConfiguration.getStandard()) {
            ++shardingStrategyConfigCount;
            if (null == yamlConfiguration.getStandard().getRangeAlgorithmClassName()) {
                result = new StandardShardingStrategyConfiguration(yamlConfiguration.getStandard().getShardingColumn(), (PreciseShardingAlgorithm)ShardingAlgorithmFactory.newInstance(yamlConfiguration.getStandard().getPreciseAlgorithmClassName(), PreciseShardingAlgorithm.class));
            } else {
                result = new StandardShardingStrategyConfiguration(yamlConfiguration.getStandard().getShardingColumn(), (PreciseShardingAlgorithm)ShardingAlgorithmFactory.newInstance(yamlConfiguration.getStandard().getPreciseAlgorithmClassName(), PreciseShardingAlgorithm.class), (RangeShardingAlgorithm)ShardingAlgorithmFactory.newInstance(yamlConfiguration.getStandard().getRangeAlgorithmClassName(), RangeShardingAlgorithm.class));
            }
        }

复合分片策略

YamlComplexShardingStrategyConfiguration
public final class YamlComplexShardingStrategyConfiguration implements YamlBaseShardingStrategyConfiguration {
    private String shardingColumns;
    private String algorithmClassName;

SQL 语句中有>>=<=<=IN 和 BETWEEN AND 等操作符,且复合分片策略支持对多个分片健操作。自定义复合分片策略要实现 ComplexKeysShardingAlgorithm 接口,重新 doSharding()方法

假设log表 user_id log_date  userId=1 log_date包含2022的到表0中查询 其他两张表查询合并

spring.shardingsphere.sharding.tables.log_t.actual-data-nodes=wim-user.log_t_$->{0..1}
spring.shardingsphere.sharding.tables.log_t.table-strategy.complex.sharding-columns=user_id, log_date
spring.shardingsphere.sharding.tables.log_t.table-strategy.complex.algorithm-class-name=com.chen.algorithm.MyComplexKeysShardingAlgorithm
public class MyComplexKeysShardingAlgorithm implements ComplexKeysShardingAlgorithm {
	
	@Override
	public Collection<String> doSharding(Collection collection, ComplexKeysShardingValue complexKeysShardingValue) {
		System.out.println(complexKeysShardingValue);
		List<String> list = (List<String>) complexKeysShardingValue.getColumnNameAndShardingValuesMap().get("user_id");
		Range range = (Range) complexKeysShardingValue.getColumnNameAndRangeValuesMap().get("log_date");
		boolean flag1 = list.contains("1");
		boolean flag2 = range.contains("2022");
		if (flag1 && flag2) {
			return Arrays.asList((String) collection.toArray()[0]);
		}
		return collection;
	}
}

Hint分片策略

YamlHintShardingStrategyConfiguration
public final class YamlHintShardingStrategyConfiguration implements YamlBaseShardingStrategyConfiguration {
    private String algorithmClassName;

这种分片策略无需配置分片健,分片健值也不再从 SQL中解析,而是由外部指定分片信息,让 SQL在指定的分库、分表中执行。ShardingSphere 通过 Hint API实现指定操作,实际上就是把分片规则tablerule 、databaserule由集中配置变成了个性化配置。

实现 HintShardingAlgorithm 接口并重写 doSharding()方法

在请求的上下文中直接指定数据库和表

spring.shardingsphere.sharding.tables.log_t.actual-data-nodes=wim-user.log_t_$->{0..1}
spring.shardingsphere.sharding.tables.log_t.table-strategy.hint.algorithm-class-name=com.chen.algorithm.MyHintShardingAlgorithm
HintManager
@GetMapping("/query/{id}")
	public String query(@PathVariable Long id) {
		HintManager hintManager = HintManager.getInstance();
		hintManager.addTableShardingValue("log_t","1");
		Log logT = logMapper.selectById(id);
		log.info("query log {}", logT);
		if (logT == null) {
			return "cannot find user";
		}
		return logT.toString();
	}
public class MyHintShardingAlgorithm implements HintShardingAlgorithm {
	
	@Override
	public Collection<String> doSharding(Collection collection, HintShardingValue hintShardingValue) {
		Object[] ds = collection.toArray();
		Object[] v = hintShardingValue.getValues().toArray();
		int index = Integer.valueOf((String) v[0]);
		return Arrays.asList((String) ds[index]);
	}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/98819.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

vue入门--2

1.计算属性和侦听器 计算属性 VS 方法 如果不使用计算属性&#xff0c;在 methods 里定义了一个方法&#xff0c;也可以实现相同的效果&#xff0c;甚至该方法还可以接受参数&#xff0c;使用起来 更灵活。 既然 methods 同样可以解决模板中复杂逻辑计算的问题&#xff0c;那么…

2266. 统计打字方案数-动态规划

2266. 统计打字方案数-动态规划 Alice 在给 Bob 用手机打字。数字到字母的 对应 如下图所示。 为了 打出 一个字母&#xff0c;Alice 需要 按 对应字母 i 次&#xff0c;i 是该字母在这个按键上所处的位置。 比方说&#xff0c;为了按出字母 s &#xff0c;Alice 需要按 7 …

语雀导出markdown的图片外链问题

本文节选自本人博客&#xff1a;https://www.blog.zeeland.cn/archives/rgoioiabeoi32 Introduction 本人因为经常使用语雀写博客&#xff0c;但是因为语雀转markdown的时候图片存在防外链行为&#xff0c;如果想要把转出的markdown发表在其他平台&#xff0c;就需要把md中所有…

计算机毕设Python+Vue邢台市公寓式月亮酒店管理系统(程序+LW+部署)

项目运行 环境配置&#xff1a; Jdk1.8 Tomcat7.0 Mysql HBuilderX&#xff08;Webstorm也行&#xff09; Eclispe&#xff08;IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持&#xff09;。 项目技术&#xff1a; SSM mybatis Maven Vue 等等组成&#xff0c;B/S模式 M…

jsp+ssm计算机毕业设计大学生心理咨询网站【附源码】

项目运行 环境配置&#xff1a; Jdk1.8 Tomcat7.0 Mysql HBuilderX&#xff08;Webstorm也行&#xff09; Eclispe&#xff08;IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持&#xff09;。 项目技术&#xff1a; JSPSSM mybatis Maven等等组成&#xff0c;B/S模式 Mave…

java计算机毕业设计springboot+vue地铁站自动售票系统-火车票售票系统

项目介绍 本系统是针对目前地铁站自动售票的实际需求,从实际工作出发,对过去的地铁站自动售票管理系统存在的问题进行分析,完善用户的使用体会。采用计算机系统来管理信息,取代人工管理模式,查询便利,信息准确率高,节省了开支,提高了工作的效率。 本系统结合计算机系统的结构…

Nacos系列——配置的创建与获取

Nacos系列——配置的创建与获取配置的创建与获取本文资源官方文档创建配置获取Nacos配置程序目录1.引入依赖完整pom2.设置yaml3.配置读取类NacosBasedProperties4.构建日志打印工具LoggerUtil5.构建Nacos基础服务类实现6.构建自动化任务实现结果配置的创建与获取 本文资源 ht…

非零基础自学Golang 第11章 文件操作 11.3 处理JSON文件 11.3.1 编码JSON

非零基础自学Golang 文章目录非零基础自学Golang第11章 文件操作11.3 处理JSON文件11.3.1 编码JSON第11章 文件操作 11.3 处理JSON文件 JSON&#xff08;JavaScript Object Notation&#xff0c;JS对象简谱&#xff09;是一种轻量级的数据交换格式。 JSON最初是属于JavaScri…

C++基础学习笔记(二)——基础入门PART2

一、数组 一个集合中&#xff0c;里面存放了相同类型的数据元素 特点1&#xff1a;数组中的每个数据元素都是相同的数据类型 特点2&#xff1a;数组是由连续的内存位置组成的 1.1 一维数组 一维数组定义的三种方式&#xff1a; 数据类型 数组名[ 数组长度 ];数据类型 数组…

高通平台开发系列讲解(充电篇)充电底层驱动 power_supply 子系统

文章目录 一、Power Supply组成二、power_supply结构体说明三、驱动接口沉淀、分享、成长,让自己和他人都能有所收获!😄 📢 电池驱动采取的是 linux 内核驱动中的power_supply子系统框架进行上报电池状态。 一、Power Supply组成 power supply framework在kernel/driver…

微服务真的是万能解药吗?

程序员宝藏库&#xff1a;https://gitee.com/sharetech_lee/CS-Books-Store DevWeekly收集整理每周优质开发者内容&#xff0c;包括开源项目、资源工具、技术文章等方面。 每周五定期发布&#xff0c;同步更新到 知乎&#xff1a;Jackpop。 欢迎大家投稿&#xff0c;提交issu…

Spring MVC学习 | 拦截器异常处理器

文章目录一、拦截器1.1 简介1.2 拦截器的使用1.2.1 创建1.2.2 配置1.2.3 测试1.3 多个拦截器的执行顺序1.3.1 preHandle()方法返回true1.3.2 preHandle()方法返回false二、异常处理器2.1 简介2.2 配置2.2.1 springmvc.xml中配置2.2.2 注解配置学习视频&#x1f3a5;&#xff1a…

编码与解码总结

标准ASC||字符集&#xff1a; ASC||&#xff1a;美国信息交换标准代码&#xff0c;包括了英文、数字等标准ASC||使用一个字节存储一个字符&#xff0c;首位是0&#xff0c;总供可以表示128个字符 GBK&#xff08;汉字内码扩展规范&#xff0c;国标&#xff09; 汉字编码字符集…

Apache Shiro,这一篇就够了

Apache Shiro&#xff0c;这一篇就够了1.Shiro实现登录拦截2.登录认证操作3.Shiro整合Mybatis4.用户授权操作5.Shiro授权6.Shiro整合Thymeleaf1.Shiro实现登录拦截 前期环境准备 准备添加Shiro的内置过滤器&#xff1a; Bean public ShiroFilterFactoryBean shiroFilterFact…

《美国职业橄榄球大联盟》:NFL·橄榄1号位

基本装备 NFL橄榄球是一项过程极为激烈的比赛&#xff0c;阻挡、拦截与冲撞都是比赛不可或缺的一部分&#xff0c;这也可以说是橄榄球的一大特色。为了保护球员的安全&#xff0c;避免因为球员受伤而耽误球赛&#xff0c; NFL与NCAA都要求所有球员必须“穿戴合适且合法的护具”…

IfcOpenShell正确设置几何体的坐标

在之前的文章中&#xff0c;我们使用 IfcOpenShell (IOS) 读取 ifc 几何并将其转换为 brep。 当我们读取 wikilab.ifc文件时&#xff0c;一切似乎都是正确的&#xff0c;但真的如此吗&#xff1f; 当你在项目中使用 BIM 时&#xff0c;坐标始终是正确讨论的主题。 就此而言&am…

Android开发如何使用Docker为Jenkins持续集成助力

Android开发如何使用Docker为持续集成助力 为什么使用Docker 我为啥要使用到Docker呢&#xff1f;其实也是被动的&#xff0c;因为公司的项目托管在Coding上面&#xff0c;然后Jenkins集成也用的是Coding的&#xff0c;Coding默认提供了Android-29&#xff0c;JDK-8的构建环境…

【JAVA进阶】多态,内部类

&#x1f4c3;个人主页&#xff1a;个人主页 &#x1f525;系列专栏&#xff1a;JAVASE基础 目录 一、多态 1.多态的概述 2.多态的优势 3.类型转换问题 二、内部类 1.内部类概述[了解] 2.静态内部类[了解] 3.成员内部类[了解] 4.匿名内部类概述[重点] 一、多态 1.多态…

树状数组经典例题

目录 1.数星星 2.小朋友排队 3.求逆序对 1.数星星 题目描述 天空中有一些星星,这些星星都是在不同的位置,每个星星都有一个坐标。 如果一个星星的左下方(包含正左和正下)有k颗星星,就说这颗星星是k级的。 例如,上图中星星5是3级的(1,2,4在它的左下),星星2,4是1级的。…

idea中推送本地仓库和远程仓库后代码回退

本地仓库代码提交后回退 提交到本地仓库后 点击提交后会保存在本地仓库 本地仓库的回撤 找到git的提交记录 右键选择撤销还原 撤销还原后会出现提交文件&#xff0c;成功将本地仓库的文件移除&#xff0c;但是本地的错误代码仍然存在 如果想撤销提交到本地仓库的错误文…