- 导入maven依赖,如下
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.shardingsphere/shardingsphere-jdbc-core-spring-boot-starter -->
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>
-
新建实体表
这个表只有两个字段,其中id不要弄成自增长的。
总共有四张表,存于两个数据库中,如下展示:
这样子就形成了对course进行分库分表了,两个数据库源,每个数据库源有两张表。 -
配置yml文件
spring:
application:
name: shardingdemo
shardingsphere:
datasource:
names: master1, master2
master1:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://xxxxxx:3306/mybatis?useUnicode=true&characterEncoding=utf8&verifyServerCertificate=false&useSSL=true
username: xxxx
password: xxxx
master2:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://xxxx:3306/db2019?useUnicode=true&characterEncoding=utf8&verifyServerCertificate=false&useSSL=true
username: xxxx
password: xxxxx
# 配置虚拟表映射
sharding:
tables:
course:
actualDataNodes: master$->{1..2}.course_$->{1..2}
databaseStrategy:
inline:
shardingColumn: id
algorithmExpression: master$->{id%2+1}
tableStrategy:
inline:
shardingColumn: id
algorithmExpression: course_$->{id%2+1}
keyGenerator:
column: id
type: SNOWFLAKE
props:
worker:
id: 1
props:
sql.show: true
其中新建了两个数据源,master1映射mybatis这个数据库,而master2映射db2019这个数据库。最后根据id的取模运算,得出,插入的新数据往哪个数据库的哪个表插入。
- 进行数据库操作
@Autowired
private CourseMapper courseMapper;
@Test
public void insertDatabaseAndTableShardingTest() {
for (int i = 0; i < 20; i++) {
Course course = new Course();
course.setName("分库分表插入" + i);
courseMapper.insert(course);
}
}
此时去到数据库中就可以看见插入的数据库了,虽然有些表没有数据,只是在测试的时候,插入的数据量不够引起的。