我问了一下官方,已经成功了。
yaml配置
spring:
application:
name: mp
main:
allow-bean-definition-overriding: true
shardingsphere:
datasource:
names: test0,test1,test2
test0:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://xxx:xxx/autotables1?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=CST
username: root
password: xxx
type: com.zaxxer.hikari.HikariDataSource
test1:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://xxx:xxx/autotables2?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=CST
username: root
password: xxx
type: com.zaxxer.hikari.HikariDataSource
test2:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://xxx:xxx/autotables3?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=CST
username: root
password: xxx
type: com.zaxxer.hikari.HikariDataSource
rules:
sharding:
auto-tables:
t_order:
actual-data-sources: test$->{0..2}
key-generate-strategy:
column: order_id
key-generator-name: snowflake
sharding-strategy:
standard:
sharding-column: order_id
sharding-algorithm-name: mod
key-generators:
snowflake:
type: MY_SNOWFLAKE2
sharding-algorithms:
mod:
type: MOD
props:
sharding-count: 6
props:
sql-show: true
通过sharding-proxy或者通过JDBC API执行create table语句,create table 是逻辑SQL
@Test
public void testInsertOrder() {
jdbcTemplate.execute("CREATE TABLE `t_order` (\n" +
" `order_id` bigint(20) NOT NULL COMMENT '订单id',\n" +
" `price` decimal(10,2) NOT NULL COMMENT '订单价格',\n" +
" `user_id` bigint(20) NOT NULL COMMENT '下单用户id',\n" +
" `status` varchar(50) NOT NULL COMMENT '订单状态',\n" +
" PRIMARY KEY (`order_id`) USING BTREE\n" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;");
Random random = new Random();
for (int i = 1; i < 10; i++) {
TOrder1 order = new TOrder1();
order.setPrice(new BigDecimal(i));
order.setUserId(Integer.valueOf(random.nextInt(25)).longValue());
order.setStatus(i + "");
orderDao.insertOrder(order);
}
}
sharding-jdbc会自动帮我们创建表,下面表都是自动创建