简介
缓解单台数据库服务器的吞吐量压力过大的情况,将数据库拆分成了主库和从库,主库负责增删改操作,从库负责查询操作
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:
# 参数配置,显示sql
props:
sql:
show: true
# 配置数据源
datasource:
# 给每个数据源取别名,下面的ds1,ds2,ds3任意取名字
names: ds1,ds2,ds3
# 给master-ds1(主库),每个数据源配置数据库连接信息
ds1:
# 配置druid数据源
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.31.16:3306/user?useUnicode=true&characterEncoding=utf8&tinyInt1isBit=false&useSSL=false&serverTimezone=GMT
#注意修改ip地址
username: root
password: root
maxPoolSize: 100
minPoolSize: 5
# 配置ds2-slave,从库
ds2:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.31.17:3306/user?useUnicode=true&characterEncoding=utf8&tinyInt1isBit=false&useSSL=false&serverTimezone=GMT
username: root
password: root
maxPoolSize: 100
minPoolSize: 5
# 配置ds3-slave,从库
ds3:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.31.17:3306/user?useUnicode=true&characterEncoding=utf8&tinyInt1isBit=false&useSSL=false&serverTimezone=GMT
username: root
password: root
maxPoolSize: 100
minPoolSize: 5
# 配置默认数据源ds1
sharding:
# 默认数据源,主要用于写,注意一定要配置读写分离 ,注意:如果不配置,那么就会把两个个节点都当做从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: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
id-type: ASSIGN_ID
3.在配置文件中允许bean定义覆盖配置项
spring:
main:
allow-bean-definition-overriding: true