Spring boot 实战 利用 Sharding-jdbc实现数据库的读写分离

sharding-jdbc 同时被 2 个专栏收录
4 篇文章 0 订阅
67 篇文章 1 订阅

读写分离原理的什么这里就不讲了,直接来看看使用 sharding-jdbc 来实现读写分离

快速入门分库分表中间件 Sharding-JDBC

对于 Sharding-JDBC 还不了解的可以参考我以前的文章 https://andyoung.blog.csdn.net/article/details/116229612

实现读写分离,先看配置

# 配置真实数据源
spring.shardingsphere.datasource.names=ds0,ds1,s0
# 配置第 1 个数据源
spring.shardingsphere.datasource.ds0.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.ds0.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.ds0.url=jdbc:mysql://localhost:3306/ds0?useUnicode=true&characterEncoding=utf8&tinyInt1isBit=false&useSSL=false&serverTimezone=GMT
spring.shardingsphere.datasource.ds0.username=root
spring.shardingsphere.datasource.ds0.password=123456
# 配置第 2 个数据源
spring.shardingsphere.datasource.ds1.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.ds1.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.ds1.url=jdbc:mysql://localhost:3306/ds1?useUnicode=true&characterEncoding=utf8&tinyInt1isBit=false&useSSL=false&serverTimezone=GMT
spring.shardingsphere.datasource.ds1.username=root
spring.shardingsphere.datasource.ds1.password=123456
# 配置第 ds0 slave 数据源
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:3306/ds0-slave?useUnicode=true&characterEncoding=utf8&tinyInt1isBit=false&useSSL=false&serverTimezone=GMT
spring.shardingsphere.datasource.s0.username=root
spring.shardingsphere.datasource.s0.password=123456
# 配置第 ds0 slave rules 主从规则
spring.shardingsphere.sharding.master-slave-rules.ds0.master-data-source-name=ds0
spring.shardingsphere.sharding.master-slave-rules.ds0.slave-data-source-names=s0
  • 配置三个数据源

  • 最后配置主从规则

    # 配置第 ds0 slave rules 主从规则
    spring.shardingsphere.sharding.master-slave-rules.ds0.master-data-source-name=ds0
    spring.shardingsphere.sharding.master-slave-rules.ds0.slave-data-source-names=s0
    

测试

 @Test
  public void masterSlaveTest() {

    TOrder tOrder = orderMapper.selectById(1387233602040721410L);
    System.out.println(tOrder);

    TOrder order = new TOrder();
    order.setOrderId(1387233602040721410L);
    order.setCreateName("订单 主库master update");
    order.setPrice(new BigDecimal("2.8"));
    orderMapper.updateById(order);

    tOrder = orderMapper.selectById(1387233602040721410L);
    System.out.println(tOrder);
  }

具体代码案列 https://github.com/andanyoung/springboot/tree/master/sharding-jdbc

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 程序猿惹谁了 设计师:白松林 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值