使用mybatisplus实现动态路由

1.pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.baomidou</groupId>
  <artifactId>dynamic-datasource-example</artifactId>
  <version>1.0.0</version>
  <packaging>jar</packaging>

  <name>dynamic-datasource-example</name>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.1.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid-spring-boot-starter</artifactId>
      <version>1.1.9</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
      <version>1.3.0</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.3.2</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>2.7.0</version>
    </dependency>
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger-ui</artifactId>
      <version>2.7.0</version>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>com.microsoft.sqlserver</groupId>
      <artifactId>sqljdbc4</artifactId>
      <version>4.0</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>


</project>
View Code

2.

spring:
  datasource:
    druid:
      stat-view-servlet:
        loginUsername: admin
        loginPassword: 123456
    dynamic:
      master:
        username: root
        password: mysql
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://192.168.37.1:3306/demo_ds_1?useUnicode=true&characterEncoding=UTF8
        druid:
          initial-size: 3
          max-active: 8
          min-idle: 2
          max-wait: -1
          min-evictable-idle-time-millis: 30000
          max-evictable-idle-time-millis: 30000
          time-between-eviction-runs-millis: 0
          validation-query: select 1
          validation-query-timeout: -1
          test-on-borrow: false
          test-on-return: false
          test-while-idle: true
          pool-prepared-statements: true
          max-open-prepared-statements: 100
          filters: stat,wall
          share-prepared-statements: true
      slave:
        one:
          username: root
          password: mysql
          driver-class-name: com.mysql.jdbc.Driver
          url: jdbc:mysql://192.168.37.1:3306/demo_ds_1?useUnicode=true&characterEncoding=UTF8
          druid:
            initial-size: 2
            max-active: 6
        two:
          username: root
          password: mysql
          driver-class-name: com.mysql.jdbc.Driver
          url: jdbc:mysql://192.168.37.1:3306/demo_ds_2?useUnicode=true&characterEncoding=UTF8
          druid:
            initial-size: 3
            max-active: 10
        sqlserver1:
                  username: 123
                  password: 123
                  driver-class-name:  com.microsoft.sqlserver.jdbc.SQLServerDriver
                  url: jdbc:sqlserver://192.168.33.1:1433;DatabaseName=DBNAME
                  druid:
                    initial-size: 3
                    max-active: 10
    initialization-mode: always
  jpa:
    hibernate:
      ddl-auto: update
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL5InnoDBDialect

logging:
  level:
    com.baomidou: debug

3.

package com.baomidou.dynamic.config;

import com.baomidou.dynamic.datasource.DynamicDataSourceStrategy;
import com.baomidou.dynamic.util.RandomNumber;
import org.springframework.context.annotation.Bean;

public class DynamicDataSourceStrategy2 implements DynamicDataSourceStrategy {


    @Override
   public String determineSlaveDataSource(String[] slaveDataSourceLookupKeys) {
        int len=slaveDataSourceLookupKeys.length;
        slaveDataSourceLookupKeys=remove(slaveDataSourceLookupKeys,"sqlserver"); //将这些读库移除,只用于@DS("sqlserver")
        slaveDataSourceLookupKeys=remove(slaveDataSourceLookupKeys,"oracle");//将这些读库移除,只用于@DS("oracle")
        int index= RandomNumber.getNumber(len-1);
        return  slaveDataSourceLookupKeys[index];
    }

    public   String  []  remove(String []arrays,String key ) {

        for (int i = 0; i < arrays.length; i++) {
            if (arrays[i].contains(key)) {
                //移除掉元素2
                for (int j = i + 1; j < arrays.length; j++) {
                    arrays[i] = arrays[j];
                }

            }
        }
        return arrays;
    }



}

4.使用自定义的数据源

package com.baomidou.dynamic.SqlserverMapper;

import com.baomidou.dynamic.datasource.DS;
import com.baomidou.dynamic.entity.Role;
import com.baomidou.dynamic.entity.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface RoleMapper {

  @Select("SELECT top 100 * FROM Role")
  @DS("sqlserver1")
  List<Role> selectAllRole();
}

5.启动应用

package com.baomidou.dynamic;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import com.baomidou.dynamic.config.DynamicDataSourceStrategy2;
import com.baomidou.dynamic.datasource.DynamicDataSourceStrategy;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)
@MapperScan("com.baomidou.dynamic.*")
public class DynamicApplication {

  public static void main(String[] args) {
    SpringApplication.run(DynamicApplication.class, args);
  }

  //将重写的访问策略,注册到容器里(@DS 时不返回sqlserver和oracle)
  @Bean
  public DynamicDataSourceStrategy dynamicDataSourceStrategy() {
    return new DynamicDataSourceStrategy2();
  }
}

 

posted @ 2018-09-11 17:36  甜菜波波  阅读(2601)  评论(0编辑  收藏  举报