SpringBoot集成Sharding-JDBC实现主从同步

1.mysql主从配置

详细内容请参考上一篇文章:MySQL8.0以上实现主从同步配置

2.application.properties文件配置

# ShardingSphere configuration
spring.shardingsphere.props.sql.show=true


spring.shardingsphere.datasource.names=m0,s0

# master DataSource configuration m0
spring.shardingsphere.datasource.m0.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.m0.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.m0.url=jdbc:mysql://localhost:3306/user_db?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.shardingsphere.datasource.m0.username=root
spring.shardingsphere.datasource.m0.password=root

# slave DataSource configuration  s0
spring.shardingsphere.datasource.s0.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.s0.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.s0.url=jdbc:mysql://localhost:3307/user_db?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.shardingsphere.datasource.s0.username=root
spring.shardingsphere.datasource.s0.password=root

# set master and slave
spring.shardingsphere.sharding.master-slave-rules.ds0.master-data-source-name=m0
spring.shardingsphere.sharding.master-slave-rules.ds0.slave-data-source-names=s0


#
spring.shardingsphere.sharding.tables.t_order.database-strategy.inline.sharding-column=user_id
spring.shardingsphere.sharding.tables.t_order.database-strategy.inline.algorithm-expression=m$->{user_id % 2 +1}


spring.shardingsphere.sharding.tables.t_user.actual-data-nodes=ds0.t_user

spring.shardingsphere.sharding.tables.t_user.table-strategy.inline.sharding-column=user_id
spring.shardingsphere.sharding.tables.t_user.table-strategy.inline.algorithm-expression=t_user

# point common table t_dict
spring.shardingsphere.sharding.broadcast-tables=t_dict

本文中主库:m0,从库:s0

3.测试

3.1 查询数据

xmlsql语句实现条件查询:

  <select id="selectOrdersByuserID" resultType="com.test.sharding.domain.pojo.User">
    select *
    from t_user
    where user_id in
    <foreach collection="userIds" item="index" open="(" separator="," close=")">
      #{index}
    </foreach>
  </select>

可以看到查询结果:

Logic SQL: select *
    from t_user
    where user_id in
     (  
      ?
     )
Actual SQL: s0 ::: select *
                  from t_user
							   where user_id in
							    (  
							     ?
							    ) ::: [1]

可看看到上面的查询语句实际上是去从库s0查了

3.2 添加数据

dao层插入语句:

    @Insert("insert into t_user(user_id,fullname,user_type) values (#{userId},#{fullname},#{userType})")
    int insertUser(User user);

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值