栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Postgre+Sharding-JDBC分库分表案例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Postgre+Sharding-JDBC分库分表案例

案例属于亲身踩坑后,去除业务逻辑,简化的一个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";

有不明白的地方,白天可以回复,晚上你懂的

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/340059.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号