來(lái)源:冰 河 發(fā)布時(shí)間:2018-11-14 11:33:06 閱讀量:1037
spring mvc+mybatis+多數(shù)據(jù)源切換 選取oracle,mysql作為例子切換數(shù)據(jù)源。oracle為默認(rèn)數(shù)據(jù)源,在測(cè)試的action中,進(jìn)行mysql和oracle的動(dòng)態(tài)切換。
web.xml
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>trac</param-value>
</context-param>
<!-- Spring的log4j監(jiān)聽(tīng)器 -->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<!-- 字符集 過(guò)濾器 -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring view分發(fā)器 -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
dispatcher.xml
<mvc:annotation-driven />
<context:component-scan base-package="com.trac" />
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
<!-- freemarker config -->
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/freemarker/" />
<property name="freemarkerVariables">
<map>
<entry key="xml_escape" value-ref="fmXmlEscape" />
</map>
</property>
<property name="freemarkerSettings">
<props>
<prop key="defaultEncoding">UTF-8</prop>
</props>
</property>
</bean>
<bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape" />
<!-- View resolvers can also be configured with ResourceBundles or XML files.
If you need different view resolving based on Locale, you have to use the
resource bundle resolver. -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="exposeRequestAttributes" value="true" />
<property name="exposeSessionAttributes" value="true" />
<property name="exposeSpringMacroHelpers" value="true" />
<property name="contentType" value="text/html;charset=UTF-8" />
<property name="cache" value="true" />
<property name="prefix" value="" />
<property name="suffix" value=".ftl" />
</bean>
applicationContext.xml
<bean id="parentDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
</bean>
<bean id="mySqlDataSource" parent="parentDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<bean id="oracleDataSource" parent="parentDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:@10.16.17.40:1531:addb"></property>
<property name="username" value="trac"></property>
<property name="password" value="trac"></property>
</bean>
<bean id="dataSource" class="com.trac.dao.datasource.DataSources">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry value-ref="mySqlDataSource" key="MYSQL"></entry>
<entry value-ref="oracleDataSource" key="ORACLE"></entry>
</map>
</property>
<property name="defaultTargetDataSource" ref="oracleDataSource"></property>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 創(chuàng)建SqlSessionFactory,同時(shí)指定數(shù)據(jù)源和mapper -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath*:com/trac/ibatis/dbcp/*.xml" />
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.trac.dao" />
</bean>
配置 parentDataSource 的父bean.再配置多個(gè)數(shù)據(jù)源繼承這個(gè)父bean,對(duì)driverClass,url,username,password,等數(shù)據(jù)源連接參數(shù)進(jìn)行各自的重寫。例如 mySqlDataSource ,在 DataSources bean中注入所有要切換的數(shù)據(jù)源,并且設(shè)置默認(rèn)的數(shù)據(jù)源。
DataSourceInstances.java
/**
* 定義數(shù)據(jù)源的標(biāo)識(shí), 和applicationContext.xml中 DataSources 的 targetDataSources 的key對(duì)應(yīng)
* @author liuyazhuang
*/
public class DataSourceInstances{
public static final String MYSQL="MYSQL";
public static final String ORACLE="ORACLE";
}
DataSourceSwitch.java
/**
*
* @author liuyazhuang
*/
public class DataSourceSwitch{
private static final ThreadLocal contextHolder=new ThreadLocal();
public static void setDataSourceType(String dataSourceType){
contextHolder.set(dataSourceType);
}
public static String getDataSourceType(){
return (String) contextHolder.get();
}
public static void clearDataSourceType(){
contextHolder.remove();
}
}
DataSources.java
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
*配置于applicationContext 中,線程局部變量ThreadLocal contextHolder 保存當(dāng)前需要的數(shù)據(jù)源類型,當(dāng) DataSourceSwitch. setDataSourceType(DataSourceInstances.XXX) 保存當(dāng)前需要的數(shù)據(jù)源類型的時(shí)候,DataSources 會(huì)從當(dāng)前線程中查找線程變量的數(shù)據(jù)源類型,從而決定使用何種數(shù)據(jù)源
* @author liuyazhuang
*/
public class DataSources extends AbstractRoutingDataSource{
@Override
protected Object determineCurrentLookupKey() {
return DataSourceSwitch.getDataSourceType();
}
}
TestAction.java
@Controller
@SuppressWarnings("unused")
public class TestAction {
@Autowired
TestMapper testMapper;
@RequestMapping("/test.action")
public ModelAndView test(
HttpServletRequest request,
HttpServletResponse resp){
ModelAndView model = new ModelAndView("test");
model.addObject("test1", "這是一個(gè)測(cè)試,獲取默認(rèn)數(shù)據(jù)連接MYSQL:"+testMapper.test());
DataSourceSwitch.setDataSourceType(DataSourceInstances.ORACLE);
model.addObject("test2", "這是一個(gè)測(cè)試,獲取數(shù)據(jù)連接ORACLE:"+testMapper.test());
DataSourceSwitch.setDataSourceType(DataSourceInstances.MYSQL);
model.addObject("test3", "這是一個(gè)測(cè)試,獲取數(shù)據(jù)連接MYSQL:"+testMapper.test());
return model;
}
}
---------------------
在線
客服
服務(wù)時(shí)間:周一至周日 08:30-18:00
選擇下列產(chǎn)品馬上在線溝通:
客服
熱線
7*24小時(shí)客服服務(wù)熱線
關(guān)注
微信
關(guān)注官方微信