springboot+mybatis+sharding-jdbc做读写分离

sharding-jdbc简介

现已更名为: sharding-sphere,官方网址如下
https://shardingsphere.apache.org/document/current/cn/overview/
简单来说,最主要的可以做以下事情:
1.数据库读写分离
2.数据库分库分表
3.分布式事务
在今天的DEMO中, 我们一起来用shard-sphere来做数据库的读写分离
主要需要以下几步:
1.准备主从的数据库,
参考文章:
https://www.javastudy.cloud/articles/2019/11/14/1573693221155.html
2.在springboot工程中,引入相应的mybatis和shard-spere的依赖
3.编写测试类

springboot+sharding-jdbc+HikariCP+mybatis做读写分离

添加依赖

 

implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.1'
runtimeOnly 'mysql:mysql-connector-java'
// 这里多了一个shardingsphere的依赖
compile group: 'org.apache.shardingsphere', name: 'sharding-jdbc-spring-boot-starter', version: '4.0.0-RC3'
 

添加springboot的配置

 

# 这里我们有一主一从
spring.shardingsphere.datasource.names=master,slave0

# 主库的配置
spring.shardingsphere.datasource.master.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.master.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.master.jdbcUrl=jdbc:mysql://localhost:33309/tools
spring.shardingsphere.datasource.master.username=root
spring.shardingsphere.datasource.master.password=javastudy

# 从库的配置
spring.shardingsphere.datasource.slave0.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.slave0.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.slave0.jdbcUrl=jdbc:mysql://localhost:33308/tools
spring.shardingsphere.datasource.slave0.username=root
spring.shardingsphere.datasource.slave0.password=javastudy

# sharding-jdbc本身的一些配置
spring.shardingsphere.masterslave.name=ms
spring.shardingsphere.masterslave.master-data-source-name=master
spring.shardingsphere.masterslave.slave-data-source-names=slave0

spring.shardingsphere.props.sql.show=true

这里要注意, 主库和从库配置的第一行, datasource.master.type 这里, 要写HikariDataSource, 这样就可以使用HikariCP了
然后平常hikariCP和Mybatis的配置照常配置就可以了, 但是不在需要spring.datasource.url,spring.datasource.username这些配置了

编写测试类

mybatis的mapper还是按原来的写法写, 然后我们使用autowire进行注入

 

@Autowired
private ArticleMapper articleMapper;

@Test
public void testDataSource(){

List<ArticleDO> articleDOS = articleMapper.listArticles(new ArticleQC());
System.out.println(articleDOS);
}

运行单元测试,可通过日志看出使用了hikariCP+sharding-jdbc

DEMO总评

读写分离是数库库量级上来后首选优化方案,就代码使用层面来说,没有大家想的那么难,建议在项目中实践起来! 大家在实践过程中遇到什么问题,欢迎随时交流

灵魂一问

有个问题我想了好久,但一直还没去验证, 和大家分享一起思考下, 就是数据库连接池是hikariCP维护的还是mybatis维护的,如何验证? 如果我调用了两次mapper文件的方法,那是使用的同一个Connection还是两个Connection?  那如果是同一个connection , 那statement是同一个还是单独的?

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值