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

本贴最后更新于 1535 天前,其中的信息可能已经时过境迁

javaDEMO

本网站记录了最全的各种 JavaDEMO ,保证下载,复制就是可用的,包括基础的, 集合的, spring 的, Mybatis 的等等各种,助力你从菜鸟到大牛,记得收藏哦~~
https://www.javastudy.cloud

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
image.png

DEMO 总评

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

  • 分布式
    78 引用 • 149 回帖 • 4 关注
  • MySQL

    MySQL 是一个关系型数据库管理系统,由瑞典 MySQL AB 公司开发,目前属于 Oracle 公司。MySQL 是最流行的关系型数据库管理系统之一。

    673 引用 • 535 回帖
  • MyBatis

    MyBatis 本是 Apache 软件基金会 的一个开源项目 iBatis,2010 年这个项目由 Apache 软件基金会迁移到了 google code,并且改名为 MyBatis ,2013 年 11 月再次迁移到了 GitHub。

    170 引用 • 414 回帖 • 440 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...