Sharding-JDBC+ Mybatis-Plus 实现读写分离

前言

Sharding-jdbc是开源的数据库操作中间件;这篇文章主要通过Sharding-JDBC 和mybatis-plus 需要的配置文件和maven依赖。

实践

一、添加maven依赖。

<dependencies>
       <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>
        
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>3.3.2version>
        dependency>

        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
            <version>8.0.13version>

        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.10version>
            <scope>compilescope>
        dependency>

        <dependency>
            <groupId>com.github.xiaoymingroupId>
            <artifactId>knife4j-spring-boot-starterartifactId>
            <version>2.0.5version>
        dependency>

        <dependency>
            <groupId>cn.hutoolgroupId>
            <artifactId>hutool-allartifactId>
            <version>5.5.7version>
        dependency>

        <dependency>
            <groupId>io.shardingspheregroupId>
            <artifactId>sharding-jdbc-spring-boot-starterartifactId>
            <version>3.1.0version>
            <exclusions>
                <exclusion>
                    <artifactId>guavaartifactId>
                    <groupId>com.google.guavagroupId>
                exclusion>
            exclusions>
        dependency>

    dependencies>

二、添加application.yml 配置文件

server:
  port: 8082
spring:
  main:
   allow-bean-definition-overriding: true #当遇到同样名字的时否允许覆盖注册候,是
sharding:
  jdbc:
    datasource:
      names: ds0,ds1
      ds0:
        driver-class-name: com.mysql.cj.jdbc.Driver
        type: com.zaxxer.hikari.HikariDataSource
        jdbc-url: jdbc:mysql://1.15.63.xxx:3306/sync_test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
        username: root
        password: 123456
      ds1:
        driver-class-name: com.mysql.cj.jdbc.Driver
        type: com.zaxxer.hikari.HikariDataSource
        jdbc-url: jdbc:mysql://1.15.63.xxx:3307/sync_test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
        username: root
        password: 123456
    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 -Plus 没有变化这里不再贴出。

从上述日志中可以发现,增删改出现在主库,而读出现在了从库
在这里插入图片描述
在这里插入图片描述

你可能感兴趣的:(mybatis,mysql,mybatis,sharding-jdbc)