天天看點

Springboot 多資料源動态切換 以AOP切點方式實作

那麼現在這篇是Springboot操作多資料源,我采用一貫的優雅方式實作:注解 ,切點的方式實作。

進入主題,

先看看這次案例項目的最終目錄結構:

Springboot 多資料源動态切換 以AOP切點方式實作

然後我這次準備的兩個不同的資料庫(多個也可以),

一個是game_message , 一個是 game_message_cluster 。 

首先先看看我們這次用到的jar,pom.xml(相關jar的作用都有相關的注釋):

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--mysql連接配接-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--Druid連接配接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>
        <!--整合mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <!--AOP-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.9</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.8.9</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

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

</project>      

然後接下來是application.yml檔案:

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driverClassName: com.mysql.jdbc.Driver
    druid:
      #第一個資料源連接配接資訊
      one:
        url: jdbc:mysql://localhost:3306/game_message?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
        username: root
        password: root
      #第二個資料源連接配接資訊
      two:
        url: jdbc:mysql://localhost:3306/game_message_cluster?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
        username: root
        password: root
      #資料庫連接配接池資訊
      initial-size: 10
      max-active: 100
      min-idle: 10
      max-wait: 60000
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 300000
      validation-query: SELECT 1 FROM DUAL
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      stat-view-servlet:
        enabled: true
        url-pattern: /druid/*
      filter:
        stat:
          log-slow-sql: true
          slow-sql-millis: 1000
          merge-sql: true
        wall:
          config:
            multi-statement-allow: true
#配置下項目端口
server:
  port: 8023
#mybatis掃描檔案路徑
mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml
#将日志檔案生成到系統盤路徑
logging:
  path: F:\\logtest\\log
  #簡單設定一下日志等級
  level:
    web: debug      

接下來我們羅列下資料源的名字,這裡簡單用ONE 、TWO 表示,DataSourceNames.java:

/**
 * @Author : JCccc
 * @CreateTime : 2019/8/28
 * @Description :
 **/

public interface DataSourceNames {
    String ONE = "ONE";
    String TWO = "TWO";
}      

接着創一個自定義注解,作為aop切點使用,DataSource.java:

import java.lang.annotation.*;

/**
 * @Author : JCccc
 * @CreateTime : 2019/8/28
 * @Description :
 **/
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DataSource {
    String value() default DataSourceNames.ONE; //預設值為ONE,因為後面我們選擇配置這個ONE為預設資料庫
}      

然後是配置AOP切點,DataSourceAspect.java:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

/**
 * @Author : JCccc
 * @CreateTime : 2019/8/28
 * @Description :
 **/
@Aspect
@Component
public class DataSourceAspect implements Ordered {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 切點: 所有配置 DataSource 注解的方法
     */
    @Pointcut("@annotation(com.example.demo.config.DataSource)")
    public void dataSourcePointCut() {}

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        DataSource ds = method.getAnnotation(DataSource.class);
        // 通過判斷 DataSource 中的值來判斷目前方法應用哪個資料源
        DynamicDataSource.setDataSource(ds.value());
        logger.info("AOP切換資料源成功,資料源為: " + ds.value());
        logger.info("set datasource is " + ds.value());
        try {
            return point.proceed();
        } finally {
            DynamicDataSource.clearDataSource();
            logger.info("clean datasource");
        }
    }

    @Override
    public int getOrder() {
        return 1;
    }
}      

到這裡切點AOP的相關配置已經完畢了,接下來到核心的動态資料源配置。

先建立手動切換資料源的核心方法類,DynamicDataSource.java:

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import javax.sql.DataSource;
import java.util.Map;

/**
 * @Author : JCccc
 * @CreateTime : 2019/8/28
 * @Description :
 **/
public class DynamicDataSource extends AbstractRoutingDataSource {
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();

    /**
     * 配置DataSource, defaultTargetDataSource為主資料庫
     */
    public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
        super.setDefaultTargetDataSource(defaultTargetDataSource);
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return getDataSource();
    }

    public static void setDataSource(String dataSource) {
        contextHolder.set(dataSource);
    }

    public static String getDataSource() {
        return contextHolder.get();
    }

    public static void clearDataSource() {
        contextHolder.remove();
    }

}      

然後是用于讀取配置資訊多資料源,并将其載入的類,DynamicDataSourceConfig.java:

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author : JCccc
 * @CreateTime : 2019/8/28
 * @Description :
 **/
@Configuration
public class DynamicDataSourceConfig {

    /**
     * 建立 DataSource Bean
     * */

    @Bean
    @ConfigurationProperties("spring.datasource.druid.one")
    public DataSource oneDataSource(){
        DataSource dataSource = DruidDataSourceBuilder.create().build();
        return dataSource;
    }

    @Bean
    @ConfigurationProperties("spring.datasource.druid.two")
    public DataSource twoDataSource(){
        DataSource dataSource = DruidDataSourceBuilder.create().build();
        return dataSource;
    }

    /**
     * 将資料源資訊載入targetDataSources
     * */

    @Bean
    @Primary
    public DynamicDataSource dataSource(DataSource oneDataSource, DataSource twoDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>(2);
        targetDataSources.put(DataSourceNames.ONE, oneDataSource);
        targetDataSources.put(DataSourceNames.TWO, twoDataSource);
        // 如果還有其他資料源,可以按照資料源one和two這種方法去進行配置,然後在targetDataSources中繼續添加
        System.out.println("加載的資料源DataSources:" + targetDataSources);

        //DynamicDataSource(預設資料源,所有資料源) 第一個指定預設資料庫
        return new DynamicDataSource(oneDataSource, targetDataSources);
    }
}      

然後是mapper層,MessageboardMapper.java:

import com.example.demo.pojo.Messageboard;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface MessageboardMapper {


    Messageboard selectByPrimaryKey(Integer id);


}      

然後對應的MessageboardMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.demo.mapper.MessageboardMapper" >
  <resultMap id="BaseResultMap" type="com.example.demo.pojo.Messageboard" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="userName" property="username" jdbcType="VARCHAR" />
    <result column="message" property="message" jdbcType="VARCHAR" />
  </resultMap>
  <sql id="Base_Column_List" >
    id, userName, message
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from messageboard
    where id = #{id,jdbcType=INTEGER}
  </select>

</mapper>      

mybatis-config.xml :

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
        <setting name="useGeneratedKeys" value="true"/>
        <setting name="useColumnLabel" value="true"/>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>      

(想了解更多的mybatis配置項,

接下來是較為關鍵的,就是service層,簡單建立一個DataSourceTestService.java:

/**
 * @Author : JCccc
 * @CreateTime : 2019/8/28
 * @Description :
 **/

import com.example.demo.config.DataSource;
import com.example.demo.config.DataSourceNames;
import com.example.demo.mapper.MessageboardMapper;
import com.example.demo.pojo.Messageboard;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class DataSourceTestService {
    @Autowired
    private MessageboardMapper messageboardMapper;

    public Messageboard testMaster(Integer userId){
        return messageboardMapper.selectByPrimaryKey(userId);
    }

    @DataSource(DataSourceNames.TWO)
    public Messageboard testCluster(Integer userId){
        return messageboardMapper.selectByPrimaryKey(userId);
    }
}      

這裡需要認真看,

@DataSource(DataSourceNames.TWO)      

這個注解标記的方法就是告訴目前方法即将切換資料源,所切換的資料源就是通過切點注解傳值,方法當被調用時,就會從切點先進入AOP進行資料源切換設定。

最後,寫一個簡單的接口來進行多資料源操作測試,

我準備的兩個資料庫裡面都有一張叫表messageboard的表,裡面的資料不一樣:

Springboot 多資料源動态切換 以AOP切點方式實作
Springboot 多資料源動态切換 以AOP切點方式實作

然後現在用接口調一下,TestController.java:

import com.example.demo.pojo.Messageboard;
import com.example.demo.service.DataSourceTestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author : JCccc
 * @CreateTime : 2019/8/28
 * @Description :
 **/
@RestController
public class TestController {
    @Autowired
    DataSourceTestService dataSourceTestServiceImpl;

    @RequestMapping("/testDbSource")
    public void testDbSource() {
        Messageboard messageboard = dataSourceTestServiceImpl.testMaster(1);
        System.out.println(messageboard.toString());
        Messageboard messageboard2 = dataSourceTestServiceImpl.testCluster(1);
        System.out.println(messageboard2.toString());
        Messageboard messageboard3 = dataSourceTestServiceImpl.testMaster(1);
        System.out.println(messageboard3.toString());
    }

}      

将項目運作,可以看到控制台列印,資料源已經都加載了:

Springboot 多資料源動态切換 以AOP切點方式實作

用postman調下接口:

Springboot 多資料源動态切換 以AOP切點方式實作

繼續閱讀