基于shard-jdbc中间件,实现数据分库分表

2024-09-08 01:08

本文主要是介绍基于shard-jdbc中间件,实现数据分库分表,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、水平分割 1、水平分库 1)、概念: 以字段为依据,按照一定策略,将一个库中的数据拆分到多个库中。 2)、结果 每个库的结构都一样;数据都不一样; 所有库的并集是全量数据; 2、水平分表 1)、概念 以字段为依据,按照一定策略,将一个表中的数据拆分到多个表中。 2)、结果 每个表的结构都一样;数据都不一样; 所有表的并集是全量数据; 二、Shard-jdbc 中间件 1、架构图

2、特点 1)、Sharding-JDBC直接封装JDBC API,旧代码迁移成本几乎为零。 2)、适用于任何基于Java的ORM框架,如Hibernate、Mybatis等 。 3)、可基于任何第三方的数据库连接池,如DBCP、C3P0、 BoneCP、Druid等。 4)、以jar包形式提供服务,无proxy代理层,无需额外部署,无其他依赖。 5)、分片策略灵活,可支持等号、between、in等多维度分片,也可支持多分片键。 6)、SQL解析功能完善,支持聚合、分组、排序、limit、or等查询。

三、项目演示 1、项目结构

springboot     2.0 版本
druid          1.1.13 版本
sharding-jdbc  3.1 版本

2、数据库配置

一台基础库映射(shard_one)两台库做分库分表(shard_two,shard_three)。
表使用:table_one,table_two

3、核心代码块

1)、数据源配置文件

spring:datasource:# 数据源:shard_onedataOne:type: com.alibaba.druid.pool.DruidDataSourcedruid:driverClassName: com.mysql.jdbc.Driverurl: jdbc:mysql://localhost:3306/shard_one?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=falseusername: rootpassword: 123initial-size: 10max-active: 100min-idle: 10max-wait: 60000pool-prepared-statements: truemax-pool-prepared-statement-per-connection-size: 20time-between-eviction-runs-millis: 60000min-evictable-idle-time-millis: 300000max-evictable-idle-time-millis: 60000validation-query: SELECT 1 FROM DUAL# validation-query-timeout: 5000test-on-borrow: falsetest-on-return: falsetest-while-idle: trueconnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000# 数据源:shard_twodataTwo:type: com.alibaba.druid.pool.DruidDataSourcedruid:driverClassName: com.mysql.jdbc.Driverurl: jdbc:mysql://localhost:3306/shard_two?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=falseusername: rootpassword: 123initial-size: 10max-active: 100min-idle: 10max-wait: 60000pool-prepared-statements: truemax-pool-prepared-statement-per-connection-size: 20time-between-eviction-runs-millis: 60000min-evictable-idle-time-millis: 300000max-evictable-idle-time-millis: 60000validation-query: SELECT 1 FROM DUAL# validation-query-timeout: 5000test-on-borrow: falsetest-on-return: falsetest-while-idle: trueconnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000# 数据源:shard_threedataThree:type: com.alibaba.druid.pool.DruidDataSourcedruid:driverClassName: com.mysql.jdbc.Driverurl: jdbc:mysql://localhost:3306/shard_three?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=falseusername: rootpassword: 123initial-size: 10max-active: 100min-idle: 10max-wait: 60000pool-prepared-statements: truemax-pool-prepared-statement-per-connection-size: 20time-between-eviction-runs-millis: 60000min-evictable-idle-time-millis: 300000max-evictable-idle-time-millis: 60000validation-query: SELECT 1 FROM DUAL# validation-query-timeout: 5000test-on-borrow: falsetest-on-return: falsetest-while-idle: trueconnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

2)、数据库分库策略

/*** 数据库映射计算*/
public class DataSourceAlg implements PreciseShardingAlgorithm<String> {private static Logger LOG = LoggerFactory.getLogger(DataSourceAlg.class);@Overridepublic String doSharding(Collection<String> names, PreciseShardingValue<String> value) {LOG.debug("分库算法参数 {},{}",names,value);int hash = HashUtil.rsHash(String.valueOf(value.getValue()));return "ds_" + ((hash % 2) + 2) ;}
}

3)、数据表1分表策略

/*** 分表算法*/
public class TableOneAlg implements PreciseShardingAlgorithm<String> {private static Logger LOG = LoggerFactory.getLogger(TableOneAlg.class);/*** 该表每个库分5张表*/@Overridepublic String doSharding(Collection<String> names, PreciseShardingValue<String> value) {LOG.debug("分表算法参数 {},{}",names,value);int hash = HashUtil.rsHash(String.valueOf(value.getValue()));return "table_one_" + (hash % 5+1);}
}

4)、数据表2分表策略

/*** 分表算法*/
public class TableTwoAlg implements PreciseShardingAlgorithm<String> {private static Logger LOG = LoggerFactory.getLogger(TableTwoAlg.class);/*** 该表每个库分5张表*/@Overridepublic String doSharding(Collection<String> names, PreciseShardingValue<String> value) {LOG.debug("分表算法参数 {},{}",names,value);int hash = HashUtil.rsHash(String.valueOf(value.getValue()));return "table_two_" + (hash % 5+1);}
}

5)、数据源集成配置

/*** 数据库分库分表配置*/
@Configuration
public class ShardJdbcConfig {// 省略了 druid 配置,源码中有/*** Shard-JDBC 分库配置*/@Beanpublic DataSource dataSource (@Autowired DruidDataSource dataOneSource,@Autowired DruidDataSource dataTwoSource,@Autowired DruidDataSource dataThreeSource) throws Exception {ShardingRuleConfiguration shardJdbcConfig = new ShardingRuleConfiguration();shardJdbcConfig.getTableRuleConfigs().add(getTableRule01());shardJdbcConfig.getTableRuleConfigs().add(getTableRule02());shardJdbcConfig.setDefaultDataSourceName("ds_0");Map<String,DataSource> dataMap = new LinkedHashMap<>() ;dataMap.put("ds_0",dataOneSource) ;dataMap.put("ds_2",dataTwoSource) ;dataMap.put("ds_3",dataThreeSource) ;Properties prop = new Properties();return ShardingDataSourceFactory.createDataSource(dataMap, shardJdbcConfig, new HashMap<>(), prop);}/*** Shard-JDBC 分表配置*/private static TableRuleConfiguration getTableRule01() {TableRuleConfiguration result = new TableRuleConfiguration();result.setLogicTable("table_one");result.setActualDataNodes("ds_${2..3}.table_one_${1..5}");result.setDatabaseShardingStrategyConfig(new StandardShardingStrategyConfiguration("phone", new DataSourceAlg()));result.setTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("phone", new TableOneAlg()));return result;}private static TableRuleConfiguration getTableRule02() {TableRuleConfiguration result = new TableRuleConfiguration();result.setLogicTable("table_two");result.setActualDataNodes("ds_${2..3}.table_two_${1..5}");result.setDatabaseShardingStrategyConfig(new StandardShardingStrategyConfiguration("phone", new DataSourceAlg()));result.setTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("phone", new TableTwoAlg()));return result;}
}

6)、测试代码执行流程

@RestController
public class ShardController {@Resourceprivate ShardService shardService ;/*** 1、建表流程*/@RequestMapping("/createTable")public String createTable (){shardService.createTable();return "success" ;}/*** 2、生成表 table_one 数据*/@RequestMapping("/insertOne")public String insertOne (){shardService.insertOne();return "SUCCESS" ;}/*** 3、生成表 table_two 数据*/@RequestMapping("/insertTwo")public String insertTwo (){shardService.insertTwo();return "SUCCESS" ;}/*** 4、查询表 table_one 数据*/@RequestMapping("/selectOneByPhone/{phone}")public TableOne selectOneByPhone (@PathVariable("phone") String phone){return shardService.selectOneByPhone(phone);}/*** 5、查询表 table_one 数据*/@RequestMapping("/selectTwoByPhone/{phone}")public TableTwo selectTwoByPhone (@PathVariable("phone") String phone){return shardService.selectTwoByPhone(phone);}
}

本文分享自微信公众号 - 知了一笑(cicada_smile)

这篇关于基于shard-jdbc中间件,实现数据分库分表的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1146684

相关文章

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

python处理带有时区的日期和时间数据

《python处理带有时区的日期和时间数据》这篇文章主要为大家详细介绍了如何在Python中使用pytz库处理时区信息,包括获取当前UTC时间,转换为特定时区等,有需要的小伙伴可以参考一下... 目录时区基本信息python datetime使用timezonepandas处理时区数据知识延展时区基本信息

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1

如何在 Spring Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义

SpringMVC 通过ajax 前后端数据交互的实现方法

《SpringMVC通过ajax前后端数据交互的实现方法》:本文主要介绍SpringMVC通过ajax前后端数据交互的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价... 在前端的开发过程中,经常在html页面通过AJAX进行前后端数据的交互,SpringMVC的controll