实验环境:
主数据库:userdb_master
从数据库:userdb_slave0,userdb_slave1
数据库各有一个表user
shardingsphere版本:4.0.0-RC3
实验没有实现数据库的主从同步,只是建了数据库叫从库。
第一步:建立数据库表
在userdb_master,userdb_slave0,userdb_slave1各建立一张表user
CREATE TABLE `user` (
`id` bigint(255) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`uid` varchar(255) DEFAULT NULL,
`school` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
)
第二步:springboot项目中引入shardingsphere,注意要引入两个包
<!-- for spring boot -->
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>4.0.0-RC3</version>
</dependency>
<!-- for spring namespace -->
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-namespace</artifactId>
<version>4.0.0-RC3</version>
</dependency>
第三步:配置application.properties
#读写分离配置,即一主多从方式配置
debug=false
server.port=8082
server.servlet.context-path=
spring.jackson.serialization.INDENT_OUTPUT=true
spring.profiles.active=
#spring.main.allow-bean-definition-overriding=true
spring.shardingsphere.datasource.names=db-master-user,db-slave-user,db-slave1-user
spring.shardingsphere.datasource.db-master-user.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.db-master-user.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.db-master-user.jdbc-url=jdbc:mysql://youripaddress:3306/userdb_master?characterEncoding=utf-8&serverTimezone=UTC
spring.shardingsphere.datasource.db-master-user.username=
spring.shardingsphere.datasource.db-master-user.password=
spring.shardingsphere.datasource.db-slave-user.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.db-slave-user.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.db-slave-user.jdbc-url=jdbc:mysql://youripaddress:3306/userdb_slave0?characterEncoding=utf-8&serverTimezone=UTC
spring.shardingsphere.datasource.db-slave-user.username=
spring.shardingsphere.datasource.db-slave-user.password=
spring.shardingsphere.datasource.db-slave1-user.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.db-slave1-user.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.db-slave1-user.jdbc-url=jdbc:mysql://youripaddress:3306/userdb_slave1?characterEncoding=utf-8&serverTimezone=UTC
spring.shardingsphere.datasource.db-slave1-user.username=
spring.shardingsphere.datasource.db-slave1-user.password=
spring.shardingsphere.masterslave.load-balance-algorithm-type=round_robin
spring.shardingsphere.masterslave.name=ds_ms
spring.shardingsphere.masterslave.master-data-source-name=db-master-user
spring.shardingsphere.masterslave.slave-data-source-names=db-slave-user,db-slave1-user
到此配置就完毕了。
第四步:验证
自己实现user表的增删改查。
验证的时候,通过代码增加一条数据,发现数据插入主库中。
查询数据的时候,需要自己手动往从库查几条数据做验证,发现代码查询的时候,会轮询去查两个从库。
到此验证完毕。