《spring 更換數據庫》要點:
本文介紹了spring 更換數據庫,希望對您有用。如果有疑問,可以聯系我們。
spring 解析之切換數據源-mysql實現版本
java探案
2017-06-08 13:13:26
主要思想:自定義一個注解,此注解標注在辦法上,通過反射解析出辦法所在的類,遍歷這個類里的所有辦法,找到注解所對應的那個辦法,調用invoke,執行辦法的過程中,用threadLocal存儲的數據源名字進行動態切換.下面進行詳細講解:
自定義一個注解,作用是標注辦法
package com.tiangou.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DataSource {
String name() default "";
}
2.ThreadLocal保留數據庫
package com.tiangou.dataSource;
public class DataSourceContextHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
public static void setDbType(String dbType) {
3.AbstractRoutingDataSource spring動態切換數據源
contextHolder.set(dbType);
}
public static String getDbType() {
return ((String) contextHolder.get());
}
public static void clearDbType() {
contextHolder.remove();
}
}
package com.tiangou.dataSource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource{
@Override
protected Object determineCurrentLookupKey() {
System.out.println(DataSourceContextHolder.getDbType());
return DataSourceContextHolder.getDbType();
}
}
4.配置文件中配置aop切面
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- 配置數據源 -->
<import resource="classpath*:mongodb.xml" />
<import resource="classpath*:redis.xml" />
<!-- <import resource="classpath*:rabbitMq.xml" /> -->
<aop:aspectj-autoproxy proxy-target-class="true"/>
<!-- 使用注解的包,包含子集 -->
<bean id="db1"
class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="jdbc:mysql://localhost:3306/tiangou?useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="db2"
class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="jdbc:mysql://localhost:3306/tiangou2?useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="dataSource" class="com.tiangou.dataSource.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="db1" value-ref="db1" />
<entry key="db2" value-ref="db2" />
</map>
</property>
<property name="defaultTargetDataSource" ref="db1" />
</bean>
<!-- 配置mybatis的sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自動掃描mappers.xml文件 -->
<property name="mapperLocations" value="classpath:com/tiangou/mapper/*.xml"></property>
<!-- mybatis配置文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean>
<!-- DAO接口所在包名,Spring會自動查找其下的類 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.tiangou.mapper" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!-- 開啟事務注解驅動 -->
<tx:annotation-driven proxy-target-class="true" order="2" />
<!-- (事務管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 配置事務通知屬性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- 定義事務傳播屬性 -->
<tx:attributes>
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="edit*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="new*" propagation="REQUIRED" />
<tx:method name="set*" propagation="REQUIRED" />
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="change*" propagation="REQUIRED" />
<tx:method name="check*" propagation="REQUIRED" />
<tx:method name="get*" propagation="REQUIRED"/>
<tx:method name="find*" propagation="REQUIRED" />
<tx:method name="load*" propagation="REQUIRED"/>
<tx:method name="*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<!-- SpringMVC在超出上傳文件限制時,會拋出
org.springframework.web.multipart.MaxUploadSizeExceededException -->
<!-- 該異常是SpringMVC在檢查上傳的文件信息時拋出來的,而且此時還沒有進入到Controller辦法中 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!-- 遇到
MaxUploadSizeExceededException異常時,自動跳轉到
/WEB-INF/error_fileupload.jsp頁面 -->
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">WEB-INF/error_fileupload</prop>
<!-- 處理其它異常(包含Controller拋出的) -->
<prop key="java.lang.Throwable">WEB-INF/500</prop>
</props>
</property>
</bean>
<!-- 配置事務切面 -->
<aop:config>
<aop:pointcut id="serviceOperation"
expression="execution(* com.tiangou.service.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />
</aop:config>
<!--
shiroQUANXIAN
-->
<!-- 繼承自AuthorizingRealm的自定義Realm,即指定Shiro驗證用戶登錄的類為自定義的ShiroDbRealm.java -->
<!-- <bean id="myRealm" class="com.tiangou.realm.MyRealm"/> -->
<!-- Shiro默認會使用Servlet容器的Session,可通過sessionMode屬性來指定使用Shiro原生Session -->
<!-- 即<property name="sessionMode" value="native"/>,詳細說明見官方文檔 -->
<!-- 這里主要是設置自定義的單Realm應用,若有多個Realm,可使用'realms'屬性代替 -->
<!-- <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> -->
<!-- <property name="realm" ref="myRealm"/> -->
<!-- </bean> -->
<!-- Shiro主過濾器自己功能十分強大,其強大之處就在于它支持任何基于URL路徑表達式的、自定義的過濾器的執行 -->
<!-- Web應用中,Shiro可控制的Web哀求必須經過Shiro主過濾器的攔截,Shiro對基于Spring的Web應用提供了完美的支持 -->
<!-- <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> -->
<!-- Shiro的核心平安接口,這個屬性是必須的 -->
<!-- <property name="securityManager" ref="securityManager"/> -->
<!-- 要求登錄時的鏈接(可根據項目的URL進行替換),非必需的屬性,默認會自動尋找Web工程根目錄下的"/login.jsp"頁面 -->
<!-- <property name="loginUrl" value="/"/> -->
<!-- 登錄成功后要跳轉的連接(本例中此屬性用不到,因為登錄成功后的處理邏輯在LoginController里硬編碼為main.jsp了) -->
<!-- <property name="successUrl" value="/system/main"/> -->
<!-- 用戶拜訪未對其授權的資源時,所顯示的連接 -->
<!-- 若想更明顯的測試此屬性可以修改它的值,如unauthor.jsp,然后用[玄玉]登錄后拜訪/admin/listUser.jsp就看見瀏覽器會顯示unauthor.jsp -->
<!-- <property name="unauthorizedUrl" value="/"/> -->
<!-- Shiro連接約束配置,即過濾鏈的定義 -->
<!-- 此處可配合我的這篇文章來理解各個過濾連的作用
http://blog.csdn.net/jadyer/article/details/12172839 -->
<!-- 下面value值的第一個'/'代表的路徑是相對于
HttpServletRequest.getContextPath()的值來的 -->
<!-- anon:它對應的過濾器里面是空的,什么都沒做,這里.do和.jsp后面的*表示參數,比喻說login.jsp?main這種 -->
<!-- authc:該過濾器下的頁面必須驗證后才能拜訪,它是Shiro內置的一個攔截器
org.apache.shiro.web.filter.authc.FormAuthenticationFilter -->
<!-- <property name="filterChainDefinitions"> -->
<!-- <value> -->
<!-- /mydemo/login=anon -->
<!-- /mydemo/getVerifyCodeImage=anon -->
<!-- /main**=authc -->
<!-- /user/info**=authc -->
<!-- /admin/listUser**=authc,perms[admin:manage] -->
<!-- </value> -->
<!-- </property> -->
<!-- </bean> -->
<!-- 保證實現了Shiro內部lifecycle函數的bean執行 -->
<!-- <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> -->
<!-- 開啟Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP掃描使用Shiro注解的類,并在必要時進行平安邏輯驗證 -->
<!-- 配置以下兩個bean即可實現此功能 -->
<!-- Enable Shiro Annotations for Spring-configured beans. Only run after the lifecycleBeanProcessor has run -->
<!-- 由于本例中并未使用Shiro注解,故注釋掉這兩個bean(個人覺得將權限通過注解的方式硬編碼在程序中,查看起來不是很方便,沒需要使用) -->
<!--
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean> -->
<!-- 自動掃描 -->
<context:component-scan base-package="com.tiangou.service,com.tiangou.aop" />
<context:component-scan base-package="com.tiangou.websocket" />
</beans>
5.對調用的辦法上進行辨別,切換數據源
以上就是動態切換數據源的講解,必要源碼的私信我,喜歡小編的給我一波關注,謝謝.
《spring 更換數據庫》是否對您有啟發,歡迎查看更多與《spring 更換數據庫》相關教程,學精學透。維易PHP學院為您提供精彩教程。