案例属于亲身踩坑后,去除业务逻辑,简化的一个demo,下面一一贴码
# 配置数据源,给数据源起名z1或z2
spring.shardingsphere.datasource.names=z1,z2
# 配置允许一个实体类映射多张表
spring.main.allow-bean-definition-overriding=true
# 配置数据源具体内容 jdbc:postgresql://
# z1
spring.shardingsphere.datasource.z1.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.z1.driver-class-name=org.postgresql.Driver
spring.shardingsphere.datasource.z1.url=jdbc:postgresql://127.0.0.1:5432/shareding
spring.shardingsphere.datasource.z1.username=postgres
spring.shardingsphere.datasource.z1.password=postgres
# z2
spring.shardingsphere.datasource.z2.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.z2.driver-class-name=org.postgresql.Driver
spring.shardingsphere.datasource.z2.url=jdbc:postgresql://127.0.0.1:5432/shareding1
spring.shardingsphere.datasource.z2.username=postgres
spring.shardingsphere.datasource.z2.password=postgres
#t3 ##############################启用水平分表的情况下配置
#spring.shardingsphere.sharding.tables.product.actual-data-nodes=z1.product_$->{1..2}
# product 主键gid 生成策略为 SNOWFLAKE,策略有很多种,也可以自己组装雪花
#spring.shardingsphere.sharding.tables.product.key-generator.column=gid
#spring.shardingsphere.sharding.tables.product.key-generator.type=SNOWFLAKE
# 指定分片策略 约定gid值是偶数添加到product_1表,如果gid是奇数添加到product_2表
#spring.shardingsphere.sharding.tables.product.table-strategy.inline.sharding-column=gid
#spring.shardingsphere.sharding.tables.product.table-strategy.inline.algorithm-expression=product_$->{gid % 2 + 1}
#t4 ##############################启动水平分库分表的情况下配置
spring.shardingsphere.sharding.tables.product.actual-data-nodes=z$->{1..2}.product_1
# 指定product表 主键gid 生成策略为 SNOWFLAKE
spring.shardingsphere.sharding.tables.product.key-generator.column=gid
spring.shardingsphere.sharding.tables.product.key-generator.type=SNOWFLAKE
# 指定数据库分片策略 约定gid值是偶数添加到z2中product_1,奇数添加到z1中product_1,说明:gid字段可以根据列名变更
spring.shardingsphere.sharding.tables.product.database-strategy.inline.sharding-column=gid
spring.shardingsphere.sharding.tables.product.database-strategy.inline.algorithm-expression=z$->{gid % 2 + 1}
上述为配置文件,有详细的配置说明,再来一代码
实体类代码:
测试类代码:
pg的建表语句:
CREATE TABLE "public"."product_1" (
"gid" numeric(64) NOT NULL,
"gname" varchar(50) COLLATE "pg_catalog"."default",
"user_id" int8,
"gstatus" varchar(255) COLLATE "pg_catalog"."default",
ConSTRAINT "product_1_pkey" PRIMARY KEY ("gid")
)
;
ALTER TABLE "public"."product_1"
OWNER TO "postgres";
有不明白的地方,白天可以回复,晚上你懂的



