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

第3篇:Sharding-JDBC(版本3.0) 入门demo,纯java 代码 【了解】

先创建ds_0,ds_1两个数据库,并同时在两个数据库中创建表t_order_0,t_order_1两个表

CREATE TABLE `t_order_0` ( `order_id` int(11) DEFAULT NULL, `user_id` int(11) DEFAULT NULL, `status` varchar(50) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;


1 新建maven项目,并添加依赖

<dependency> <groupId>io.shardingsphere</groupId> <artifactId>sharding-jdbc-core</artifactId> <version>3.0.0</version> </dependency> <!-- mysql 数据库驱动. --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.31</version> </dependency> <!-- 数据源 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.26</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency>

2 编写主类并测试

import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.Properties; import javax.sql.DataSource; import com.alibaba.druid.pool.DruidDataSource; import com.mysql.cj.jdbc.Driver; import io.shardingsphere.api.config.ShardingRuleConfiguration; import io.shardingsphere.api.config.TableRuleConfiguration; import io.shardingsphere.api.config.strategy.InlineShardingStrategyConfiguration; import io.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory; public class ShardTest_1 { // 通过Druid构建数据源. public DataSource createDataSource(String url, String username, String password) { DruidDataSource ds = new DruidDataSource(); // driver : 数据库驱动. url: 数据库地址 username/pwd : 账号和密码 ds.setDriverClassName(Driver.class.getName()); ds.setUrl(url); ds.setUsername(username); ds.setPassword(password); return ds; } /** * 通过ShardingDataSourceFactory 构建分片数据源 * * @return * @throws SQLException */ public DataSource getShardingDataSource() throws SQLException { /* * 1. 数据源集合:dataSourceMap * * 2. 分片规则:shardingRuleConfig * */ // 配置真实数据源 Map<String, DataSource> dataSourceMap = new HashMap<String, DataSource>(); // 添加数据源.两个数据源ds_0和ds_1 dataSourceMap.put("ds_0", createDataSource( "jdbc:mysql://localhost:3306/ds_0?useUnicode=true&allowMultiQueries=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&tinyInt1isBit=false&useSSL=false", "root", "123456")); dataSourceMap.put("ds_1", createDataSource( "jdbc:mysql://localhost:3306/ds_1?useUnicode=true&allowMultiQueries=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&tinyInt1isBit=false&useSSL=false", "root", "123456")); /** * 需要构建表规则 1. 指定逻辑表. 2. 配置实际节点》 3. 指定主键字段. 4. 分库和分表的规则》 * * 数据库:ds_0和ds_1 表:t_order_0 和 t_order_1 t_order表的字段 (order_id,user_id,status) * * 表的分片策略 order_id 库的分片策略 user_id */ // 配置t_order表规则 TableRuleConfiguration orderTableRuleConfiguration = new TableRuleConfiguration(); // 指定逻辑表 orderTableRuleConfiguration.setLogicTable("t_order"); // 配置实际节点 // ds_0.t_order_0 , ds_0.t_order_1, ds_1.t_order_0 , ds_1.t_order_1 orderTableRuleConfiguration.setActualDataNodes("ds_${0..1}.t_order_${0..1}"); // 指定主键字段 orderTableRuleConfiguration.setKeyGeneratorColumnName("order_id"); // 表的分片策略根据 order_id,分成t_order_0,t_order_1两个表 orderTableRuleConfiguration.setTableShardingStrategyConfig( new InlineShardingStrategyConfiguration("order_id", "t_order_${order_id%2}")); // 数据库的分片策略 根据user_id,分成ds_0,ds_1两个数据库 orderTableRuleConfiguration.setDatabaseShardingStrategyConfig( new InlineShardingStrategyConfiguration("user_id", "ds_${user_id%2}")); // 分片规则:shardingRuleConfig ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration(); shardingRuleConfig.getTableRuleConfigs().add(orderTableRuleConfiguration); DataSource ds = ShardingDataSourceFactory.createDataSource(dataSourceMap, shardingRuleConfig, new HashMap<String, Object>(), new Properties()); return ds; } /** * 3. 编写测试例子: 通过DataSource获取到Connection. * * @param args * @throws SQLException */ public static void main(String[] args) throws SQLException { /* * 1. 需要到DataSource 2. 通过DataSource获取Connection 3. 定义一条SQL语句. 4. * 通过Connection获取到PreparedStament. 5. 执行SQL语句. 6. 关闭连接. */ ShardTest_1 app = new ShardTest_1(); // * 1. 需要到DataSource DataSource dataSource = app.getShardingDataSource(); // * 2. 通过DataSource获取Connection Connection connection = dataSource.getConnection(); // * 3. 定义一条SQL语句. // 注意:******* sql语句中 使用的表是 上面代码中定义的逻辑表 ******* String sql = "insert into t_order(order_id,user_id,status) values(10,1,'insert')"; // * 4. 通过Connection获取到PreparedStament. PreparedStatement preparedStatement = connection.prepareStatement(sql); // * 5. 执行SQL语句. preparedStatement.execute(); sql = "insert into t_order(order_id,user_id,status) values(11,2,'insert')"; preparedStatement = connection.prepareStatement(sql); preparedStatement.execute(); // * 6. 关闭连接. preparedStatement.close(); connection.close(); } }

运行结果:当用户id为1时,数据到ds_1数据库
当用户id为2时,数据到ds_0数据库

当order_id为10时,到表t_order_0中
当order_id为11时,到表t_order_1中

http://www.cnnetsun.cn/news/2132634.html

相关文章:

  • Google Earth Engine(GEE) ——使用sentinel-1中VV和VH波段来进行土地分类(随机森林分类方法)
  • Open Library API深度解析:构建全球图书数据生态的终极方案
  • 如何快速实现Android屏幕共享:3步完成专业级屏幕录制开发
  • iwrqk:如何用Flutter打造完美的Iwara移动体验
  • **基于Python的多智能体系统实现:从理论到实战落地**在现代分布式计算与人工智能交叉领域,**多智能体系
  • pandas使用笔记、数据清洗、json_normalize
  • MDX-M3-Viewer:轻松查看魔兽争霸3和星际争霸2游戏模型
  • C++、C语言和JAVA开发的区别
  • 用Matlab给信号“搬家”:手把手教你将中频采样数据转为IQ格式(附完整代码)
  • Smithbox终极指南:如何轻松修改你最喜欢的魂系游戏
  • 如何用MaaFramework在5分钟内构建你的第一个自动化测试项目:从零到一的完整指南
  • 保姆级教程:在若依Vue前后端分离项目中,一步步集成Activiti7工作流引擎
  • Viper配置加密方案:安全存储敏感配置信息的终极指南
  • 卡梅德生物技术快报|抗体纯化:双抗抗体纯化工艺开发:复合模式层析参数优化与 DoE 应用实践
  • 告别循环漏洞:testify断言库的边界验证终极实战指南
  • 2025届必备的五大AI论文平台推荐榜单
  • 终极指南:uBlock Origin如何守护你的数据隐私?GDPR合规与隐私保护全解析
  • Windows Cleaner:免费高效的Windows系统清理工具,彻底告别C盘爆红烦恼
  • 2048游戏AI助手:三步掌握数字合并的终极策略
  • 完整指南:解决Pixelle-Video TTS语音生成失败的常见问题
  • Gramps家谱软件完全指南:从零开始构建你的家族历史数据库
  • 终极指南:如何用WebAssembly扩展Caddy服务器功能
  • 如何理解编译器工作原理:the-super-tiny-compiler终极指南
  • DSU Sideloader:安卓双系统的终极安全安装指南
  • Phi-3.5-mini-instruct多行业落地:电商客服应答、保险条款解读、制造业SOP简化案例
  • React Native Draggable FlatList:终极拖拽排序组件完全指南
  • OpenClaw从入门到应用——Agent:模型供应商(Model Providers)
  • Phi-3-mini-4k-instruct-gguf从零开始:中小企业低成本AI助手搭建指南
  • 3个突破性方法:如何利用AnimateAnyone彻底改变角色动画制作
  • AI模型优化五大核心技术解析与实践