動(dòng)態(tài)數(shù)據(jù)源切換

背景

有一個(gè)使用C#的老項(xiàng)目,原來設(shè)計(jì)的時(shí)候是根據(jù)一個(gè)區(qū)域一個(gè)數(shù)據(jù)庫的設(shè)計(jì),現(xiàn)在需要將這個(gè)項(xiàng)目重構(gòu)成Java的項(xiàng)目。并且新增動(dòng)態(tài)添加區(qū)域,不用重啟數(shù)據(jù)庫的需求。

PS:原來添加區(qū)域步驟
1.手動(dòng)新建數(shù)據(jù)庫
2.手動(dòng)錄入該區(qū)域的靜態(tài)數(shù)據(jù)
3.手動(dòng)將數(shù)據(jù)庫鏈接復(fù)制到主庫
4.重新運(yùn)行程序

需求

1.可以動(dòng)態(tài)的通過接口添加數(shù)據(jù)庫
2.可以根據(jù)規(guī)則動(dòng)態(tài)的切換數(shù)據(jù)源

解決方案

Spring boot提供了AbstractRoutingDataSource 根據(jù)用戶定義的規(guī)則選擇當(dāng)前的數(shù)據(jù)源,這樣我們可以在執(zhí)行查詢之前,設(shè)置使用的數(shù)據(jù)源。而切換的數(shù)據(jù)源存在于targetDataSources對(duì)象中,并且提供了setTargetDataSources讓我們來動(dòng)態(tài)設(shè)置數(shù)據(jù)源。所以解決方案就有了,

1.新建一個(gè)單例的動(dòng)態(tài)數(shù)據(jù)源類

繼承AbstractRoutingDataSource,并且重寫其determineCurrentLookupKey(切換時(shí)指定數(shù)據(jù)源)和setTargetDataSources方法。新增createDataSource來動(dòng)態(tài)添加數(shù)據(jù)源,linkDatasource判斷數(shù)據(jù)源是否可用。

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSONObject;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import rfpatrolsystem.entity.Substation;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Map;

/**
 * 動(dòng)態(tài)數(shù)據(jù)源
 *
 * @author admin
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

    private static DynamicDataSource instance;

    static Map<Object, Object> dynamicTargetDataSources;

    public static DynamicDataSource getInstance() {
        if (instance == null) {
            synchronized (DynamicDataSource.class) {
                if (instance == null) {
                    instance = new DynamicDataSource();
                }
            }
        }
        return instance;
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return DbContextHolder.getDataSourceKey();
    }

    @Override
    public void setTargetDataSources(Map<Object, Object> targetDataSources) {
        super.setTargetDataSources(targetDataSources);
        dynamicTargetDataSources = targetDataSources;
    }

    /**
     * 創(chuàng)建數(shù)據(jù)源
     *
     * @param key        數(shù)據(jù)源名稱
     * @param driveClass 數(shù)據(jù)源類型
     * @param url        數(shù)據(jù)源連接字符串
     * @param username   用戶名
     * @param password   密碼
     * @return 添加是否成功
     */
    public boolean createDataSource(String key, String driveClass, String url, String username, String password) {
        try {
            if (!linkDatasource(driveClass, url, username, password)) {
                return false;
            }
            DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.setName(key);
            druidDataSource.setDriverClassName(driveClass);
            druidDataSource.setUrl(url);
            druidDataSource.setUsername(username);
            druidDataSource.setPassword(password);
            druidDataSource.setMaxWait(60000);
            druidDataSource.setFilters("stat");
            druidDataSource.init();
            Map<Object, Object> dynamicTargetDataSources2 = dynamicTargetDataSources;
            // 加入map
            dynamicTargetDataSources2.put(key, druidDataSource);
            // 將map賦值給父類的TargetDataSources
            this.setTargetDataSources(dynamicTargetDataSources2);
            // 將TargetDataSources中的連接信息放入resolvedDataSources管理
            super.afterPropertiesSet();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 判斷數(shù)據(jù)庫是否能連接
     *
     * @param driveClass 連接驅(qū)動(dòng)
     * @param url        連接地址
     * @param username   用戶名
     * @param password   密碼
     * @return 連接是否成功
     */
    private boolean linkDatasource(String driveClass, String url, String username, String password) {
        Connection connection = null;
        try {
            // 排除連接不上的錯(cuò)誤
            Class.forName(driveClass);
            //
            DriverManager.setLoginTimeout(1);
            // 相當(dāng)于連接數(shù)據(jù)庫
            connection = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            return false;
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

}

2.動(dòng)態(tài)數(shù)據(jù)源切換,使用ThreadLocal和線程綁定


/**
 * 動(dòng)態(tài)數(shù)據(jù)源
 *
 * @author admin
 */
public class DbContextHolder {

    /**
     * 綁定當(dāng)前線程
     */
    private static ThreadLocal<String> dataSourceKey = new ThreadLocal<>();


    /**
     * 設(shè)置當(dāng)前線程使用的數(shù)據(jù)源key
     *
     * @param dataSourceType 數(shù)據(jù)源key
     */
    public static void setDataSourceKey(String dataSourceType) throws BusinessException {
        // 數(shù)據(jù)源中沒有這個(gè)key
        if (DynamicDataSource.dynamicTargetDataSources == null || DynamicDataSource.dynamicTargetDataSources.get(dataSourceType) == null) {
            throw new BusinessException(ExceptionMsg.DATABASE_ERROR);
        }
        dataSourceKey.set(dataSourceType);
    }

    /**
     * 獲取當(dāng)前線程使用的數(shù)據(jù)源key
     *
     * @return 數(shù)據(jù)源key
     */
    static String getDataSourceKey() {
        return dataSourceKey.get();
    }

    /**
     * 清楚數(shù)據(jù)源
     */
    static void clearDataSourceKey() {
        dataSourceKey.remove();
    }

}

3.數(shù)據(jù)源配置

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 數(shù)據(jù)源配置
 *
 * @author admin
 */
@Configuration
public class DataSourceConfig {

    @Autowired
    private Environment env;

    @Value("${spring.datasource.names}")
    private String datasourceNames;

    /**
     * 默認(rèn)數(shù)據(jù)源
     *
     * @return 默認(rèn)數(shù)據(jù)源
     */
    private DataSource getDefaultDataSource() {
        DruidDataSource defaultDS = new DruidDataSource();
        defaultDS.setUrl(env.getProperty("spring.datasource.base.url"));
        defaultDS.setUsername(env.getProperty("spring.datasource.base.username"));
        defaultDS.setPassword(env.getProperty("spring.datasource.base.password"));
        defaultDS.setDriverClassName(env.getProperty("spring.datasource.base.driver-class-name"));
        return defaultDS;
    }

    /**
     * 已經(jīng)配置的動(dòng)態(tài)數(shù)據(jù)源。
     */
    private Map<Object, Object> getDataSources() {
        Map<Object, Object> map = new HashMap<>(2);
        if (datasourceNames != null && datasourceNames.length() > 0) {
            String[] names = datasourceNames.split(",");
            for (String name : names) {
                DruidDataSource dataSource = new DruidDataSource();
                dataSource.setUrl(env.getProperty("spring.datasource." + name + ".url"));
                dataSource.setUsername(env.getProperty("spring.datasource." + name + ".username"));
                dataSource.setPassword(env.getProperty("spring.datasource." + name + ".password"));
                dataSource.setDriverClassName(env.getProperty("spring.datasource." + name + ".driver-class-name"));
                dataSource.setBreakAfterAcquireFailure(true);
                dataSource.setConnectionErrorRetryAttempts(0);
                map.put(name, dataSource);
            }
        }
        return map;
    }

    @Bean
    public DynamicDataSource dynamicDataSource() {
        DynamicDataSource dynamicDataSource = DynamicDataSource.getInstance();
        Map<Object, Object> dataSources = getDataSources();
        if (dataSources.size() > 0) {
            dynamicDataSource.setTargetDataSources(dataSources);
        }
        DataSource ds = getDefaultDataSource();
        if (ds != null) {
            dynamicDataSource.setDefaultTargetDataSource(ds);
        }
        return dynamicDataSource;
    }

    @Bean(name = "sqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dynamicDataSource") DataSource dynamicDataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dynamicDataSource);
        return bean.getObject();
    }
}

4.使用AOP實(shí)現(xiàn)數(shù)據(jù)源切換

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import rfpatrolsystem.contant.Const;
import rfpatrolsystem.result.BusinessException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 利用aop原理實(shí)現(xiàn)切換數(shù)據(jù)源
 *
 * @author admin
 */
@Aspect
@Component
public class TargetDataSourceAspect {

    /**
     * 根據(jù)session的name值設(shè)置不同的DataSource
     */
    @Before("execution(* com.yugioh.mapper.*.*(..))")
    public void changeDataSource() throws BusinessException {
        if (DbContextHolder.getDataSourceKey() == null) {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = null;
            HttpSession session = null;
            String dbCode = null;
            if (servletRequestAttributes != null) {
                request = servletRequestAttributes.getRequest();
            }
            if (request != null) {
                dbCode = (String) request.getAttribute(Const.SESSION_DB_CODE);
                session = request.getSession();
            }
            if (dbCode == null && session != null) {
                dbCode = (String) session.getAttribute(Const.SESSION_DB_CODE);
            }
            if (dbCode != null) {
                DbContextHolder.setDataSourceKey(dbCode);
            }
        }
    }

    /**
     * 方法執(zhí)行完之后清楚當(dāng)前數(shù)據(jù)源,讓其使用默認(rèn)數(shù)據(jù)源
     */
    @After("execution(* com.yugioh.mapper.*.*(..))")
    public void restoreDataSource() {
        DbContextHolder.clearDataSourceKey();
    }
}

后續(xù)使用

1.添加數(shù)據(jù)源使用:DynamicDataSource.getInstance().createDatasourece
2.在切面中自定義數(shù)據(jù)源的切換規(guī)則

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容