Sharding-Jdbc 读写分离(Spring Boot)

2019-01-25  本文已影响22人  黄靠谱

参考

中文官网
http://shardingsphere.io/document/current/cn/manual/sharding-jdbc/configuration/config-spring-namespace/

配置参考官网:
http://shardingsphere.io/document/current/cn/manual/sharding-jdbc/configuration/config-spring-boot/

demo

https://github.com/huangzhenshi/shardingjdbc_springboot

读写分离

核心功能

配置:(SpringBoot + 读写分离)

  1. 数据库准备:
  1. 配置一主多从数据源:master、slave0、slave1
  2. 配置从库的访问策略:随机、轮询(默认)、自定义 :randomStrategy
  3. 整合多个数据源:masterslave
sharding.jdbc.datasource.names=master,slave0,slave1

sharding.jdbc.datasource.master.type=com.alibaba.druid.pool.DruidDataSource
sharding.jdbc.datasource.master.driver-class-name=com.mysql.jdbc.Driver
sharding.jdbc.datasource.master.url=jdbc:mysql://localhost:3306/testsync?characterEncoding=utf-8
sharding.jdbc.datasource.master.username=root
sharding.jdbc.datasource.master.password=123456

sharding.jdbc.datasource.slave0.type=com.alibaba.druid.pool.DruidDataSource
sharding.jdbc.datasource.slave0.driver-class-name=com.mysql.jdbc.Driver
sharding.jdbc.datasource.slave0.url=jdbc:mysql://192.168.29.129:3306/testsync?characterEncoding=utf-8
sharding.jdbc.datasource.slave0.username=huangzs
sharding.jdbc.datasource.slave0.password=123456

sharding.jdbc.datasource.slave1.type=com.alibaba.druid.pool.DruidDataSource
sharding.jdbc.datasource.slave1.driver-class-name=com.mysql.jdbc.Driver
sharding.jdbc.datasource.slave1.url=jdbc:mysql://192.168.29.130:3306/testsync?characterEncoding=utf-8
sharding.jdbc.datasource.slave1.username=huangzs
sharding.jdbc.datasource.slave1.password=123456

sharding.jdbc.config.masterslave.load-balance-algorithm-type=round_robin
sharding.jdbc.config.masterslave.name=dataSource
sharding.jdbc.config.masterslave.master-data-source-name=master
sharding.jdbc.config.masterslave.slave-data-source-names=slave0,slave1

sharding.jdbc.config.props.sql.show=true
  1. jar包依赖:springBoot版本
        <dependency>
            <groupId>io.shardingjdbc</groupId>
            <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
            <version>2.0.0.M3</version>
        </dependency>

API

  1. 强制走主库查询
HintManager.getInstance().setMasterRouteOnly();
上一篇 下一篇

猜你喜欢

热点阅读