什么是Sharding-JDBC:
步骤:
①、首先我们在我们的POM中导入我们的maven坐标
②、在我们的配置文件application中配置我们的读写分离规则和数据库,连接池等等一系列
server:
port: 8080
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
spring:
shardingsphere:
datasource:
names:
master,slave
# 主数据源
master:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.138.100:3306/rw?characterEncoding=utf-8
username: root
password: root
# 从数据源
slave:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.138.101:3306/rw?characterEncoding=utf-8
username: root
password: root
masterslave:
# 读写分离配置
load-balance-algorithm-type: round_robin #轮询
# 最终的数据源名称
name: dataSource
# 主库数据源名称
master-data-source-name: master
# 从库数据源名称列表,多个逗号分隔
slave-data-source-names: slave
props:
sql:
show: true #开启SQL显示,默认false
此时我们如果启动我们的项目的话,会报错,原因是因为数据源起冲突了。因为我们的导入的Sharding_JDBC会为我们建一个数据源
但是我们的druid连接词也会为我们建一个数据源,这样他们就起冲突了。
所以我们还得在后面加上:
spring.main.allow-bean-definition-overriding: true
才可以。
测试:
根据我们以上的yaml配置进行测试:
使用我们的postMan进行GET请求:
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@da9d610] was not registered for synchronization because synchronization is not active
JDBC Connection [org.apache.shardingsphere.shardingjdbc.jdbc.core.connection.MasterSlaveConnection@36e29d5] will not be managed by Spring
==> Preparing: SELECT id,name,age,address FROM user WHERE id=?
2022-08-12 11:09:04.790 INFO 15412 --- [nio-8080-exec-6] ShardingSphere-SQL : Rule Type: master-slave
2022-08-12 11:09:04.790 INFO 15412 --- [nio-8080-exec-6] ShardingSphere-SQL : SQL: SELECT id,name,age,address FROM user WHERE id=? ::: DataSources: slave
==> Parameters: 1234(Long)
<== Columns: id, name, age, address
<== Row: 1234, ebdbbd, 23, 莆田
<== Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@da9d610]
可以看到我们的get请求是由我们的slave来进行查询的
使用postMan进行post请求:
2022-08-12 11:13:02.995 INFO 15412 --- [nio-8080-exec-9] ShardingSphere-SQL : Rule Type: master-slave
2022-08-12 11:13:02.995 INFO 15412 --- [nio-8080-exec-9] ShardingSphere-SQL : SQL: INSERT INTO user ( id,
name,
age,
address ) VALUES ( ?,
?,
?,
? ) ::: DataSources: master
2022-08-12 11:13:02.997 ERROR 15412 --- [nio-8080-exec-9] c.a.druid.pool.DruidAbstractDataSource : discard long time none received connection. , jdbcUrl : jdbc:mysql://192.168.31.126:3306/rw?characterEncoding=utf-8, jdbcUrl : jdbc:mysql://192.168.31.126:3306/rw?characterEncoding=utf-8, lastPacketReceivedIdleMillis : 1210836
==> Parameters: 5678(Long), 小明(String), 21(Integer), 中国(String)
<== Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5e8c2f78]
可以看到我们是使用我们的master进行保存的