springboot+mybatisplus读写分离小demo

1.数据库主从同步配置可参考https://blog.csdn.net/YYpawn/article/details/87808107

2.引入依赖



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.3.RELEASE
         
    
    com.mysql
    masterslave
    0.0.1-SNAPSHOT
    masterslave
    Demo project for Spring Boot

    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
        
            com.baomidou
            mybatisplus-spring-boot-starter
            1.0.5
        
        
            com.baomidou
            mybatis-plus
            2.1.8
        
        
            org.springframework.boot
            spring-boot-starter-jdbc
        
        
        
        
            mysql
            mysql-connector-java
            5.1.34
            runtime
        
        
        
            org.apache.velocity
            velocity-engine-core
            2.0
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.3.1
        
        
        
            com.baomidou
            dynamic-datasource-spring-boot-starter
            2.4.2
        
        
        
            org.projectlombok
            lombok
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


3.数据库配置

server:
  port: 8555
spring:
  datasource:
    dynamic:
      primary: master
      datasource:
        master:
          username: root
          password: root
          driver-class-name: com.mysql.jdbc.Driver
          url: jdbc:mysql://192.168.0.252:3306/istest?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
        slave_1:
          username: root
          password: root
          driver-class-name: com.mysql.jdbc.Driver
          url: jdbc:mysql://192.168.0.65:3306/istest?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
logging:
  config: classpath:logback-spring.xml
  level:
    root: debug
mybatis-plus:
  mapper-locations: classpath:/mapper/*.xml
  typeAliasesPackage: com.mysql.masterslave.model.entity

4.mybatisplus配置

springboot+mybatisplus读写分离小demo_第1张图片

5.编写测试类

springboot+mybatisplus读写分离小demo_第2张图片

6.测试,访问localhost:8555/user/add,主库从库都写入数据,控制台显示

springboot+mybatisplus读写分离小demo_第3张图片

访问查询接口,localhost:8555/user/list,控制台显示

springboot+mybatisplus读写分离小demo_第4张图片

此过程中关键引入dynamic-datasource-spring-boot-starter 依赖,在service使用@RS()注解,不传参默认使用主库,@DS("slave_1")使用slave_1库。

demo地址: https://github.com/YYpawns/springboot-mybatis.git

你可能感兴趣的:(收集)