1、数据库读写分离可参考
https://blog.csdn.net/weixin_43205308/article/details/129774068
2、application.properties配置
#中文官网地址https://shardingsphere.apache.org/index_zh.html
#配置数据源名称,可以随便起,多数据源
spring.shardingsphere.datasource.names=m3,s0
#第一个数据源
#配置一个实体类对应两张表,不然会报Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
spring.main.allow-bean-definition-overriding = true
#主数据源
spring.shardingsphere.datasource.m3.type = com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.m3.driver-class-name = com.mysql.jdbc.Driver
spring.shardingsphere.datasource.m3.url = jdbc:mysql://192.168.102.48:3306/user_db?serverTimezone=GMT%2B8&characterEnconding=UTF-8
spring.shardingsphere.datasource.m3.username = root
spring.shardingsphere.datasource.m3.password = ****
#从数据源
spring.shardingsphere.datasource.s0.type = com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.s0.driver-class-name = com.mysql.jdbc.Driver
spring.shardingsphere.datasource.s0.url = jdbc:mysql://localhost:3306/user_db?serverTimezone=GMT%2B8&characterEnconding=UTF-8
spring.shardingsphere.datasource.s0.username = root
spring.shardingsphere.datasource.s0.password = ****
#主从库逻辑数据源定义 ds0为user_db,主从统一名称叫ds0
spring.shardingsphere.sharding.master-slave-rules.ds0.master-data-source-name=m3
spring.shardingsphere.sharding.master-slave-rules.ds0.slave-data-source-names=s0
#配置user_db数据库里面t_user专库专表
#spring.shardingsphere.sharding.tables.t_user.actual-data-nodes = m$->{3}.t_user
#因为是主从配置了,读写分离所以换成统一名称叫ds0
spring.shardingsphere.sharding.tables.t_user.actual-data-nodes = ds0.t_user
#指定t_user表里面主键生成策略 SNOWFLAKE表示雪花算法 user_id为表的主键
spring.shardingsphere.sharding.tables.t_user.key-generator.column=user_id
spring.shardingsphere.sharding.tables.t_user.key-generator.type=SNOWFLAKE
#指定分片策略,约定cid值偶数添加到course_1表,如果cid是奇数,添加到course_2表
spring.shardingsphere.sharding.tables.t_user.table-strategy.inline.sharding-column = user_id
#因为数据库的表是1,2所以需要+1,不然的话会把数据库加到不同的表里面
spring.shardingsphere.sharding.tables.t_user.table-strategy.inline.algorithm-expression =t_user
# 打开sql输出日志
spring.shardingsphere.props.sql.show = true
3、测试代码
@Test
void addUser() {
//测试添加代码
User user=new User();
user.setUsername("chenkl2");
user.setUstatus("a");
userDao.insert(user);
}
@Test
void getUser() {
//测试添加代码
QueryWrapper<User> wrapper = new QueryWrapper<User>().eq("user_id", 101L);
wrapper =wrapper.eq("user_id",100L);
User user = userDao.selectOne(wrapper);
System.out.println(user);
}