先创建好数据库和表,maven添加依赖,可参考博文
https://blog.csdn.net/qq_41712271/article/details/105708447
1 在main/resources目录下,创建sharding.yaml文件
# 真实数据源配置,这里的ds_0,ds_1会在下面的配置中引用
dataSources:
#可配置多个: !!数据库连接池实现类
ds_0: !!com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/ds_0?useSSL=false
username: root
password: 123456
ds_1: !!com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/ds_1?useSSL=false
username: root
password: 123456
#分库分表配置,可配置多个逻辑表
shardingRule:
tables:
#指定逻辑表
t_order:
#指定主键字段
keyGeneratorColumnName: order_id
#配置实际节点,这里的ds就是引用上面定义的名称
actualDataNodes: ds_${0..1}.t_order_${0..1}
#数据库的分片策略 根据user_id,分成ds_0,ds_1两个数据库
databaseStrategy:
inline:
shardingColumn: user_id
algorithmExpression: ds_${user_id % 2}
#表的分片策略根据 order_id,分成t_order_0,t_order_1两个表
tableStrategy:
inline:
shardingColumn: order_id
algorithmExpression: t_order_${order_id % 2}
#属性配置(可选)
props:
#是否开启SQL显示,默认值: false
sql.show: true
#executor.size: 工作线程数量,默认值: CPU核数
2 编写测试类进行测试
package net.huawei.shardingjdbc_study_1;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.sql.DataSource;
import io.shardingsphere.shardingjdbc.api.yaml.YamlShardingDataSourceFactory;
/**
* 1. 通过Druid构建数据源.
* 2. 通过ShardingDataSourceFactory 构建分片数据源.
* 3. 编写测试例子:
* 通过DataSource获取到Connection.
*/
public class App2 {
/**
* 3. 编写测试例子: 通过DataSource获取到Connection.
*
* @param args
* @throws SQLException
* @throws IOException
*/
public static void main(String[] args) throws SQLException, IOException {
/*
* 1. 需要到DataSource
* 2. 通过DataSource获取Connection
* 3. 定义一条SQL语句.
* 4. 通过Connection获取到PreparedStament.
* 5. 执行SQL语句.
* 6. 关闭连接.
*/
// * 1. 需要到DataSource
String filePath = App2.class.getResource("/sharding.yaml").getFile();
DataSource dataSource = YamlShardingDataSourceFactory.createDataSource(new File(filePath));
// * 2. 通过DataSource获取Connection
Connection connection = dataSource.getConnection();
// * 3. 定义一条SQL语句.
// ######sql语句中使用的表名,是定义的逻辑表######
String sql = "insert into t_order(order_id,user_id,status) values(99,11,'insert')";
// * 4. 通过Connection获取到PreparedStament.
PreparedStatement preparedStatement = connection.prepareStatement(sql);
// * 5. 执行SQL语句.
preparedStatement.execute();
connection = dataSource.getConnection();
sql = "insert into t_order(order_id,user_id,status) values(100,12,'insert')";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.execute();
// * 6. 关闭连接.
preparedStatement.close();
connection.close();
System.out.println("结束");
}
}