Sharding-JDBC — 读写分离(spring boot)

折月煮酒 提交于 2019-12-06 08:32:45

我们的项目,很多都涉及到了数据库的操作。数据库的稳定性显得尤为重要。互联网公司很多都采用“一主多从”的实现方案,我这里也不例外。这样可以大大减少主库的读压力,从而提高数据库性能!

同时,选择一套靠谱的中间件来实现读写分离,也尤为重要。通常有几个选择:

  1. AOP切面实现数据源的切换。
  2. sharding-jdbc、tddl等jdbc增强版的数据库中间件。
  3. mycat、atlas等代理层的数据库中间件。

这里,考虑到性能需求,我选择了sharding-jdbc。

 

直接上实现!

依赖

下面两个依赖,根据选择的版本不同,选择的依赖包不同:

  • Sharding-Sphere版:(3.0及之后的版本)
    <dependency>
        <groupId>io.shardingsphere</groupId>
        <artifactId>sharding-jdbc</artifactId>
        <version>${latest.release.version}</version>
    </dependency>
  • Sharding-JDBC版:(3.0之前的版本)
    <!-- 引入sharding-jdbc核心模块 -->
    <dependency>
        <groupId>io.shardingjdbc</groupId>
        <artifactId>sharding-jdbc-core-spring-boot-starter</artifactId>
        <version>2.0.3</version>
    </dependency>

     

配置

sharding:
  jdbc:
    datasource:
      names: ds_master,ds_slave_0,ds_slave_1
      ds_master:
        type: org.apache.commons.dbcp.BasicDataSource
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://10.112.1.1:3306/gome_axwl_fc?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
        username: test
        password: test
      ds_slave_0:
        type: org.apache.commons.dbcp.BasicDataSource
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://10.112.1.2:3306/gome_axwl_fc?useUnicode=true&characterEncoding=utf-8
        username: test
        password: test
      ds_slave_1:
        type: org.apache.commons.dbcp.BasicDataSource
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://10.112.1.3:3306/gome_axwl_fc?useUnicode=true&characterEncoding=utf-8
        username: test
        password: test

    config:
      masterslave:
        load-balance-algorithm-type: round_robin
        name:
          ds_ms
        master-data-source-name:
          ds_master
        slave-data-source-names:
          ds_slave_0,ds_slave_1

这里配置了一个主库(ds_master),两个从库(ds_slave_0、ds_slave_1)。
从库的读取规则为round_robin(轮询策略),除了轮询策略,还有支持random(随机策略)。

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!