Sharding-jdbc實現水平分表
阿新 • • 發佈:2020-07-19
1、搭建環境
(1)SpringBoot2.2.1+MyBatisPlus+Sharding-JDBC+Druid連線池
(2)建立SpringBoot工程,版本2.2.1
(3)引入相關依賴
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.20</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>sharding-jdbc-spring-boot-starter</artifactId> <version>4.0.0-RC1</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.5</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
2、按照水平分表的方式建立資料庫,建立資料庫表
(1)建立資料庫 course_db
(2)在資料庫中建立兩張表 course_1 和 course_2
(3)約定一種規則:如果新增的課程id是偶數,把資料新增到course_1
如果是基數,則新增到course2
3、編寫程式碼,完成對分庫分表後資料的操作
(1)建立實體類,mapper
4、配置sharding-jdbc的分片策略
(1)在專案的配置檔案中進行配置
#sharding-jdbc 分片策略
# 資料來源名稱,多資料來源以逗號分隔
spring.shardingsphere.datasource.names=m1
#配置資料來源的詳細資訊
# 資料庫連線池
spring.shardingsphere.datasource.m1.type=com.alibaba.druid.pool.DruidDataSource
#資料庫驅動類名
spring.shardingsphere.datasource.m1.driver-class-name= com.mysql.cj.jdbc.Driver
# 資料庫 URL 連線
spring.shardingsphere.datasource.m1.url=jdbc:mysql://localhost:3306/course_db?serverTimezone=GMT%2B8
# 資料庫使用者名稱
spring.shardingsphere.datasource.m1.username= root
# 資料庫密碼
spring.shardingsphere.datasource.m1.password=houchen
# 指定course表的分佈情況,配置在哪個資料庫,表名稱是什麼 m1.course_1 m1.course_2
spring.shardingsphere.sharding.tables.course.actual-data-nodes=m1.course_$->{1..2}
#指定course表中主鍵的生成策略 SNOWFLAKE:雪花演算法,隨機生成主鍵Id
spring.shardingsphere.sharding.tables..course.key-generator.column= = cid
spring.shardingsphere.sharding.tables..course.key-generator.type= =SNOWFLAKE
# 指定分片的策略 約定cid值 : 偶數--》course_1 奇數-->course_2
spring.shardingsphere.sharding.tables.course.table-strategy.inline.sharding-column= cid
spring.shardingsphere.sharding.tables.course.table-strategy.inline.algorithm-expression=course_$->{cid%2 +1}
#開啟sql的輸出日誌
spring.shardingsphere.props.sql.show = true
5、編寫測試程式碼
@RunWith(SpringRunner.class) @SpringBootTest public class ShardingJdbcDdemoApplicationTest { @Autowired private CourseMapper courseMapper; @Test public void testInsert(){ Course course =new Course(); course.setCname("java"); course.setUserId(100L); course.setCstatus("normal"); courseMapper.insert(course); } }