水平分表
引入jar包
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>4.0.0-RC1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.16</version>
</dependency>
application.properties配置
#项目名称
spring.application.name=demo
#端口号
server.port=8089
#mysql数据库连接
spring.datasource.url=jdbc:mysql://localhost:3306/demo?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
server.servlet.context-path = /demo
spring.http.encoding.enabled = true
spring.http.encoding.charset = UTF-8
spring.http.encoding.force = true
spring.main.allow-bean-definition-overriding = true
mybatis.configuration.map-underscore-to-camel-case = true
#sharding-jdbc分片规则配置
#数据源
spring.shardingsphere.datasource.names = demo
spring.shardingsphere.datasource.demo.type = com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.demo.driver-class-name = com.mysql.jdbc.Driver
spring.shardingsphere.datasource.demo.url = jdbc:mysql://localhost:3306/demo?useUnicode=true
spring.shardingsphere.datasource.demo.username = root
spring.shardingsphere.datasource.demo.password = root
#指定 address 表的数据分布情况,address是表的前缀, 配置数据节点 demo.address_1 => address_1 ,demo.address_2 => address_2
#分多少表 分片键 就到多少 $->{1,10}
spring.shardingsphere.sharding.tables.address.actual-data-nodes=demo.address_$->{1..3}
#指定address表的主键生成策略为 雪花算法 SNOWFLAKE
spring.shardingsphere.sharding.tables.address.key-generator.column=id
spring.shardingsphere.sharding.tables.address.key-generator.type=SNOWFLAKE
# 指定address表的分片策略,分片策略包括分片键和分片算法;
# id:主键。计算表的后缀 :id_?; $->{id % 2 + 1} = 偶数0 + 1 = 1 即 id_1 ; $->{id % 2 + 1} = 奇数 1 + 1 = 2 即 id_2
# 分几个表 分片键就除以几 {id % 10 + 1}
spring.shardingsphere.sharding.tables.address.table-strategy.inline.sharding-column=id
spring.shardingsphere.sharding.tables.address.table-strategy.inline.algorithm-expression=address_$->{id % 3 + 1}
#打开SQL输出日志
spring.shardingsphere.props.sql.show=true
标签:分库,spring,shardingsphere,address,idea,datasource,demo,sharding From: https://www.cnblogs.com/javaazj/p/18617611