简介
缓解单台数据库服务器的吞吐量压力过大的情况,将数据库拆分成了主库和从库,主库负责增删改操作,从库负责查询操作
Sharding -JDBC
一种轻量级的java框架,在java的jdbc层提供的额外服务,可兼容JDBC和各种ORM框架,使用Sharding-JDBC可实现程序运行过程中的数据读写分离
maven依赖
读写分离的实现
1.导入sharding-jdbc依赖坐标
<dependency><groupId>org.apache.shardingsphere</groupId><artifactId>sharding-jdbc-spring-boot-starter</artifactId><version>4.1.1</version> <!-- 替换为最新版本 -->
</dependency>
2.在配置文件中配置读写分离规则
server:port: 8080
spring:main:allow-bean-definition-overriding: true //sharding-jdbc生成的数据源覆盖druid生成的数据源shardingsphere:# 参数配置,显示sqlprops:sql:show: true# 配置数据源datasource:# 给每个数据源取别名,下面的ds1,ds2,ds3任意取名字names: ds1,ds2,ds3# 给master-ds1(主库),每个数据源配置数据库连接信息ds1:# 配置druid数据源type: com.alibaba.druid.pool.DruidDataSourcedriver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://192.168.31.16:3306/user?useUnicode=true&characterEncoding=utf8&tinyInt1isBit=false&useSSL=false&serverTimezone=GMT#注意修改ip地址username: rootpassword: rootmaxPoolSize: 100minPoolSize: 5# 配置ds2-slave,从库ds2:type: com.alibaba.druid.pool.DruidDataSourcedriver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://192.168.31.17:3306/user?useUnicode=true&characterEncoding=utf8&tinyInt1isBit=false&useSSL=false&serverTimezone=GMTusername: rootpassword: rootmaxPoolSize: 100minPoolSize: 5# 配置ds3-slave,从库ds3:type: com.alibaba.druid.pool.DruidDataSourcedriver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://192.168.31.17:3306/user?useUnicode=true&characterEncoding=utf8&tinyInt1isBit=false&useSSL=false&serverTimezone=GMTusername: rootpassword: rootmaxPoolSize: 100minPoolSize: 5# 配置默认数据源ds1sharding:# 默认数据源,主要用于写,注意一定要配置读写分离 ,注意:如果不配置,那么就会把两个个节点都当做从slave节点,新增,修改和删除会出错。default-data-source-name: ds1# 配置数据源的读写分离,但是数据库一定要做主从复制masterslave:# 配置主从名称,可以任意取名字name: ms# 配置主库master,负责数据的写入master-data-source-name: ds1# 配置从库slave节点slave-data-source-names: ds2,ds3# 配置slave节点的负载均衡均衡策略,采用轮流查询机制load-balance-algorithm-type: round_robin
# 整合mybatisplus的配置XXXXX
mybatis-plus:configuration:map-underscore-to-camel-case: truelog-impl: org.apache.ibatis.logging.stdout.StdOutImplglobal-config:db-config:id-type: ASSIGN_ID
3.在配置文件中允许bean定义覆盖配置项
spring:main:allow-bean-definition-overriding: true