Sharding-Jdbc实现读写分离
Hello,兄弟们好,我是Feri,最近整理了最新的基于Seata-Server2.0实现分布式事务的demo,希望对你有所帮助,有任何问题,可以随时沟通交流,在成为技术大牛的路上,我们一路前行!
之前的一篇文章,实现了Mysql的主从复制,那么本篇就接着上次搭建Mysql的主从复制,咱们使用Sharding-Jdbc实现一下读写分离,来提升Mysql访问的瓶颈,来,手把手带你飞!
之前搭建的4台Mysql服务器
基于Sharding-Jdbc实现Mysql集群下的读写分离操作步骤:
1.准备数据库和表
-- 在主库 创建数据库,在从库观察 是否会同步createdatabase db_test01;createtable db_test01.t_msg(
id intprimarykeyauto_increment,
title varchar(20),
info varchar(100),
ctime datetime);
1.创建SpringBoot项目并依赖jar
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.22</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.3.1</version></dependency><dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-openapi3-spring-boot-starter</artifactId><version>4.4.0</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.apache.shardingsphere</groupId><artifactId>sharding-jdbc-spring-boot-starter</artifactId><version>4.1.1</version></dependency></dependencies>
2.实现t_msg表的CRUD操作
3.在application.yaml实现配置
spring:shardingsphere:props:sql:#打印代理的sql语句show:truedatasource:#配置对应的数据源names: dbmaster,dbslaver1,dbslaver2,dbslaver3
dbmaster:driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://127.0.0.1:3310/db_test01
username: root
password:123456dbslaver1:driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://127.0.0.1:3312/db_test01
username: root
password:123456dbslaver2:driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://127.0.0.1:3313/db_test01
username: root
password:123456dbslaver3:driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://127.0.0.1:3314/db_test01
username: root
password:123456masterslave:#主从复制的配置,配置读写分离name: ms
master-data-source-name: dbmaster #设置主库,写库slave-data-source-names: dbslaver1,dbslaver2,dbslaver3 #设置从库,读库load-balance-algorithm-type: round_robin #设置从库的负载均衡策略,支持2种:1.轮询 2.随机 randommybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
4.运行测试
测试新增接口和查询接口,观察后台运行日志
这样就可以啦,希望对你能有所帮助哈,少走弯路,就关注我!
版权归原作者 Coding Sir 所有, 如有侵权,请联系我们删除。