Sharding Sphere 读写分离配置(四)

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
#因为数据库的表是12所以需要+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);

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值