使用 YAML 配置
引入 Maven 依赖
<dependency><groupId>org.apache.shardingsphere</groupId><artifactId>shardingsphere-jdbc-core</artifactId><version>${shardingsphere.version}</version></dependency>
规则配置
ShardingSphere-JDBC 的 YAML 配置文件 通过数据源集合、规则集合以及属性配置组成。 以下示例是根据 user_id 取模分库, 且根据 order_id 取模分表的 2 库 2 表的配置。
注:示例的数据库连接池为HikariCP,可根据业务场景更换为其他主流数据库连接池。
# 配置真实数据源dataSources:# 配置第 1 个数据源ds0: !!com.zaxxer.hikari.HikariDataSourcedriverClassName: com.mysql.jdbc.DriverjdbcUrl: jdbc:mysql://localhost:3306/ds0username: rootpassword:# 配置第 2 个数据源ds1: !!com.zaxxer.hikari.HikariDataSourcedriverClassName: com.mysql.jdbc.DriverjdbcUrl: jdbc:mysql://localhost:3306/ds1username: rootpassword:rules:# 配置分片规则- !SHARDINGtables:# 配置 t_order 表规则t_order:actualDataNodes: ds${0..1}.t_order${0..1}# 配置分库策略databaseStrategy:standard:shardingColumn: user_idshardingAlgorithmName: database_inline# 配置分表策略tableStrategy:standard:shardingColumn: order_idshardingAlgorithmName: table_inlinet_order_item:# 省略配置 t_order_item 表规则...# ...# 配置分片算法shardingAlgorithms:database_inline:type: INLINEprops:algorithm-expression: ds${user_id % 2}table_inline:type: INLINEprops:algorithm-expression: t_order_${order_id % 2}
// 创建 ShardingSphereDataSourceDataSource dataSource = YamlShardingSphereDataSourceFactory.createDataSource(yamlFile);
使用 ShardingSphereDataSource
通过 YamlShardingSphereDataSourceFactory 工厂创建的 ShardingSphereDataSource 实现自 JDBC 的标准接口 DataSource。 可通过 DataSource 选择使用原生 JDBC,或JPA, MyBatis 等 ORM 框架。
DataSource dataSource = YamlShardingSphereDataSourceFactory.createDataSource(yamlFile);String sql = "SELECT i.* FROM t_order o JOIN t_order_item i ON o.order_id=i.order_id WHERE o.user_id=? AND o.order_id=?";try (Connection conn = dataSource.getConnection();PreparedStatement ps = conn.prepareStatement(sql)) {ps.setInt(1, 10);ps.setInt(2, 1000);try (ResultSet rs = preparedStatement.executeQuery()) {while(rs.next()) {// ...}}}