读写分离代码实现(springboot):sharding-jdbc

    技术2026-10-09  2

    一、sharding-jdbc实现读写分离

    引入sharding-jdbc依赖

    <!-- sharding jdbc --> <dependency> <groupId>io.shardingsphere</groupId> <artifactId>sharding-jdbc-spring-boot-starter</artifactId> <version>3.1.0</version> </dependency>

    yml配置文件 

    sharding: jdbc: datasource: names: ds0,ds1 ds0: ## 主库 type: com.alibaba.druid.pool.DruidDataSource driver-class: com.mysql.jdbc.Driver url: jdbc:mysql://192.168.152.16:3339/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC username: root password: 123456 maxPoolSize: 50 minPoolSize: 1 ds1: ## 从库 type: com.alibaba.druid.pool.DruidDataSource driver-class: com.mysql.jc.jdbc.Driver url: jdbc:mysql://192.168.152.16:3340/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC username: root password: 123456 maxPoolSize: 50 minPoolSize: 1 config: sharding: default-data-source-name: ds0 masterslave: name: ms master-data-source-name: ds0 slave-data-source-names: ds1 props: sql.show: true mybatis: configuration: map-underscore-to-camel-case: true type-aliases-package: com.sxt.pojo

    如此简单,完成!

     

     

    Processed: 0.011, SQL: 9