SSM框架、Druid鏈接池實現多數據源配置(已上線使用)

整體大概流程:java

  一、配置數據源、帳密(帳密一致,文章很少闡述)mysql

  driverClassName = com.mysql.jdbc.Driver
  validationQuery = SELECT 1 FROM DUALspring

# 腕錶
jdbc_url = jdbc:mysql://127.0.0.1:3306/do_wave_new?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true

# 車機
jdbc_url2 = jdbc:mysql://127.0.0.1:3306/car_internet?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true

jdbc_username = root
jdbc_password = dowave!@#888
jdbc_initialSize = 2 jdbc_minIdle = 1 jdbc_maxActive = 500 jdbc_maxWait = 1800000

 

  二、Mybytis.xml 配置數據源sql

   <!-- 配置數據源 -->
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="driverClassName" value="${driverClassName}" /> 
        <property name="url" value="${jdbc_url}" />
        <property name="username" value="${jdbc_username}" />
        <property name="password" value="${jdbc_password}" />

        <!-- 初始化鏈接大小 -->
        <property name="initialSize" value="${jdbc_initialSize}" />
        <!-- 鏈接池最大使用鏈接數量 -->
        <property name="maxActive" value="${jdbc_maxActive}" />
        <!-- 鏈接池最小空閒 -->
        <property name="minIdle" value="${jdbc_minIdle}" />
        <!-- 獲取鏈接最大等待時間 毫秒-->
        <property name="maxWait" value="${jdbc_maxWait}" />

        <!-- 打開PSCache,而且指定每一個鏈接上PSCache的大小 -->
        <property name="poolPreparedStatements" value="true" /> 
        <property name="maxPoolPreparedStatementPerConnectionSize" value="33" />

        <property name="validationQuery" value="${validationQuery}" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />

        <!-- 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!-- 配置一個鏈接在池中最小生存的時間,單位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000" />

        <!-- 超過期間限制是否回收: 打開removeAbandoned功能 -->
        <property name="removeAbandoned" value="true" />
        <!-- 超時時間:1800秒,也就是30分鐘 -->
        <property name="removeAbandonedTimeout" value="1800" />
        <!-- 關閉abanded鏈接時輸出錯誤日誌 -->
        <property name="logAbandoned" value="true" />

        <!-- 監控數據庫 -->
        <!-- <property name="filters" value="mergeStat" /> -->
        <property name="filters" value="stat" />
        
        <!-- 非公平鎖 -->
        <property name="useUnfairLock" value="true" />
    </bean>
    
    <!-- 配置數據源 -->
    <bean name="dataSource2" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
          <property name="driverClassName" value="${driverClassName}" /> 
        <property name="url" value="${jdbc_url2}" />
        <property name="username" value="${jdbc_username}" />
        <property name="password" value="${jdbc_password}" />

        <!-- 初始化鏈接大小 -->
        <property name="initialSize" value="${jdbc_initialSize}" />
        <!-- 鏈接池最大使用鏈接數量 -->
        <property name="maxActive" value="${jdbc_maxActive}" />
        <!-- 鏈接池最小空閒 -->
        <property name="minIdle" value="${jdbc_minIdle}" />
        <!-- 獲取鏈接最大等待時間 毫秒-->
        <property name="maxWait" value="${jdbc_maxWait}" />

        <!-- 打開PSCache,而且指定每一個鏈接上PSCache的大小 -->
        <property name="poolPreparedStatements" value="true" /> 
        <property name="maxPoolPreparedStatementPerConnectionSize" value="33" />

        <property name="validationQuery" value="${validationQuery}" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />

        <!-- 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!-- 配置一個鏈接在池中最小生存的時間,單位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000" />

        <!-- 超過期間限制是否回收: 打開removeAbandoned功能 -->
        <property name="removeAbandoned" value="true" />
        <!-- 超時時間:1800秒,也就是30分鐘 -->
        <property name="removeAbandonedTimeout" value="1800" />
        <!-- 關閉abanded鏈接時輸出錯誤日誌 -->
        <property name="logAbandoned" value="true" />

        <!-- 監控數據庫 -->
        <!-- <property name="filters" value="mergeStat" /> -->
        <property name="filters" value="stat" />
        
        <!-- 非公平鎖 -->
        <property name="useUnfairLock" value="true" />
    </bean>
    
    <bean id="dynamicDataSource" class="com.dowave.datasource.DynamicDataSource">
        <property name="targetDataSources">
            <map key-type="java.lang.String">
                <!-- 主庫-腕錶 -->
                <entry key="ds1" value-ref="dataSource"/>
                <!-- 副庫-車機 -->
                <entry key="ds2" value-ref="dataSource2"/>
            </map>
        </property>
        <!--默認數據源-->
        <property name="defaultTargetDataSource" ref="dataSource"/>
    </bean>

    <!-- myBatis文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dynamicDataSource" />
        <!-- 自動掃描entity目錄, 省掉Configuration.xml裏的手工配置 -->
        <property name="mapperLocations" value="classpath:com/XXXXXX/entity/mapper/*.xml" />
    </bean>

 

  三、數據源切換工具類數據庫

    枚舉類:表明對應的數據源express

public enum DataSourceEnum {

    DS1("ds1"), DS2("ds2");

    private String key;

    DataSourceEnum(String key) {
        this.key = key;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }
}

 

    建立建立 DynamicDataHolder 用於持有當前線程中使用的數據源標識mybatis

public class DataSourceHolder {
    private static final ThreadLocal<String> dataSources = new ThreadLocal<String>();

    public static void setDataSources(String dataSource) {
        dataSources.set(dataSource);
    }

    public static String getDataSources() {
        return dataSources.get();
    }
}

 

    建立DynamicDataSource的類,繼承AbstractRoutingDataSource並重寫determineCurrentLookupKey方法app

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class DynamicDataSource extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceHolder.getDataSources();
    }

}

 

  四、自動切換數據源,利用AOP,進行自動切換數據源
建立切面類 DataSourceExchange,切面的規則能夠自定義,根據本身的項目作本身的規則,我這邊用 citn 表示不一樣的數據源。
ide

public class DataSourceExchange {

    public void before(JoinPoint point) {

        // 獲取目標對象的類類型
        Class<?> aClass = point.getTarget().getClass();
        String c = aClass.getName();
        String[] s = c.split("\\.");
        // 獲取包名用於區分不一樣數據源
        String packageName = s[3];

        if ("citn".equals(packageName)) {
            DataSourceHolder.setDataSources(DataSourceEnum.DS2.getKey());
            System.out.println("數據源:" + DataSourceEnum.DS2.getKey());
        } else {
            DataSourceHolder.setDataSources(DataSourceEnum.DS1.getKey());
            System.out.println("數據源:" + DataSourceEnum.DS1.getKey());
        }
    }

    /**
     * 執行後將數據源置爲默認
     */
    public void after() {
        DataSourceHolder.setDataSources(DataSourceEnum.DS1.getKey());
    }

}

 

  五、Spring.xml 配置AOP切面,expression 爲切入點,根據本身項目調整。工具

 

   <bean id="dataSourceExchange" class="com.dowave.datasource.DataSourceExchange" />
    
    <aop:config>
        <aop:aspect ref="dataSourceExchange">
            <aop:pointcut id="dataSourcePointcut" expression="execution(* com.XXXXXX.**.service.impl.*ServiceImpl.*(..))" />
            <aop:before pointcut-ref="dataSourcePointcut" method="before" />
            <aop:after pointcut-ref="dataSourcePointcut" method="after" />
        </aop:aspect>
    </aop:config>

 

  六、須要使用其餘數據源在 *ServiceImpl 的位置切換數據源便可

@Service
public class AdminServiceImpl implements IAdminService {
    @Autowired
    private AdminDao adminDao;
    @Autowired
    private AgentDao agentDao;
    @Autowired
    private AdminAgentDao adminAgentDao;

    @Override
    public Admin login(AdminForm form) {
        DataSourceHolder.setDataSources(DataSourceEnum.DS2.getKey());
        return adminDao.login(form);
    }
}

 

 

附:結構目錄

相關文章
相關標籤/搜索