通过shardingsphere实现mysql读写分离
2021-06-21 本文已影响0人
各种萌新
先引依赖 环境就不说了 就springboot那一套 我自己搭的简陋框架 也没做过多的封装 也没引太多的依赖
<!--druid数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.16</version>
</dependency>
<!--shardingsphere最新版本-->
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>4.0.0-RC1</version>
</dependency>
我用的配置文件是application.properties 写入主表从表的配置
server.port=8081
# 同名允许覆盖注册
spring.main.allow-bean-definition-overriding=true
spring.shardingsphere.datasource.names=master,slave0
# 数据源 主库
spring.shardingsphere.datasource.master.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.master.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.master.url=jdbc:mysql://localhost:3306/master?characterEncoding=utf-8&serverTimezone=UTC
spring.shardingsphere.datasource.master.username=root
spring.shardingsphere.datasource.master.password=123456
# 数据源 从库
spring.shardingsphere.datasource.slave0.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.slave0.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.slave0.url=jdbc:mysql://localhost:3306/slave?characterEncoding=utf-8&serverTimezone=UTC
spring.shardingsphere.datasource.slave0.username=root
spring.shardingsphere.datasource.slave0.password=123456
# 读写分离
spring.shardingsphere.masterslave.load-balance-algorithm-type=round_robin
spring.shardingsphere.masterslave.name=ms
spring.shardingsphere.masterslave.master-data-source-name=master
spring.shardingsphere.masterslave.slave-data-source-names=slave0
#打印sql
spring.shardingsphere.props.sql.show=true
启动报错了,具体报啥错我忘记记录了,有一个错误是需要我在启动类上加一句排除自动加载数据源,我查了一下如果不加会自动查找 application.yml 或者 properties 文件里的 spring.datasource.* 相关属性并自动配置单数据源,因为这时候要配置多数据源,所以要手动。
//加入的就是(exclude= {DataSourceAutoConfiguration.class})
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
正常来说应该用mysql集群或者再找几个不同地址数据库来做一下主从关系注册,来实现数据同步,但是我懒惰了就先实现一下读写分离吧。