ssm中使用两个数据库,通过注解方式切换数据源

1、在配置文件jdbc.properties中,配置两个数据库例如:


jdbc.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.url=jdbc:sqlserver://192.168.0.154:1433;DatabaseName=PenalizeAPI_UP
jdbc.username=chn
jdbc.password=ChangNeng!2369

jdbc.driverClassName_test=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.url_test=jdbc:sqlserver://192.168.0.160:1433;databaseName=Penalize20170416
jdbc.username_test=chn
jdbc.password_test=Changneng12369


druid.initialSize=50
druid.maxActive=100
druid.minIdle=15

2、在spring-Mybatis.xml中加载jdbc文件,配置datasource。


<!-- scanner jdbc properties  -->
<context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true"/>

<!-- 连接另一个数据库 -->
<bean id="dateSource_second" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 数据库驱动 -->
        <property name="driverClassName" value="${jdbc.driverClassName_test}" />
        <!-- 连接URL串 -->
        <property name="url" value="${jdbc.url_test}" />
        <!-- 连接用户名 -->
        <property name="username" value="${jdbc.username_test}" />
        <!-- 连接密码 -->
        <property name="password" value="${jdbc.password_test}" />
        
        <!-- 配置初始化大小 -->  
        <property name="initialSize" value="${druid.initialSize}" />  
        <!-- 配置初始化最大 连接数 -->  
        <property name="maxActive" value="${druid.maxActive}" />  
        <!-- 配置初始化最小连接数 -->  
        <property name="minIdle" value="${druid.minIdle}" />  
        <!-- 配置获取连接等待超时的时间 -->  
        <property name="maxWait" value="60000" />  
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->  
        <property name="timeBetweenEvictionRunsMillis" value="20000" />  
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->  
        <property name="minEvictableIdleTimeMillis" value="300000" />  
        <!-- 检测连接是否有效的SQL -->  
        <property name="validationQuery" value="SELECT 'x' " />  
        <property name="testWhileIdle" value="false" />  
        <property name="testOnBorrow" value="false" />  
        <property name="testOnReturn" value="false" />  
        <!-- MySQL不需要做PSCache,只有Oracle/DB2/SQL Server之类支持游标的数据库才需要配置成true -->  
        <property name="poolPreparedStatements" value="false" />  
        <!-- 如果是Oracle/DB2/SQL Server之类支持游标的数据库需要加上一下配置 -->  
        <property name="maxPoolPreparedStatementPerConnectionSize" value="50" /> 
        <!-- durib监控,否则不显示数据 -->
        <property name="filters" value="stat"></property>
</bean>
 
   <!--数据库连接-->  
    <bean id="dataSource_first" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">   
      <!-- 数据库驱动 -->
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <!-- 连接URL串 -->
        <property name="url" value="${jdbc.url}" />
        <!-- 连接用户名 -->
        <property name="username" value="${jdbc.username}" />
        <!-- 连接密码 -->
        <property name="password" value="${jdbc.password}" />
        
        <!-- 配置初始化大小 -->  
        <property name="initialSize" value="${druid.initialSize}" />  
        <!-- 配置初始化最大 连接数 -->  
        <property name="maxActive" value="${druid.maxActive}" />  
        <!-- 配置初始化最小连接数 -->  
        <property name="minIdle" value="${druid.minIdle}" />  
  
    </bean> 

<!-- 下面的是切换数据库的自定义类 -->
<bean id="multipleDataSource" class="com.changneng.penalize.business.datasource.MultipleDataSource">
<property name="defaultTargetDataSource" ref="dataSource_first"></property>
<property name="targetDataSources">
<map>
<entry key="dataSource_first" value-ref="dataSource_first"></entry>
<entry key="dateSource_second" value-ref="dateSource_second"></entry>
</map>
</property>
</bean>




<!-- myBatis mapping文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="multipleDataSource" />
<!-- 指定MyBatis配置文件 -->
        <property name="configLocation" value="classpath:mybatis-config.xml" />
<!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 -->
<property name="mapperLocations" value="classpath*:com/changneng/penalize/business/mapper/*.xml" />
</bean>

<!-- 自动扫描dao包下的所有类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.changneng.penalize.business.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>


<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="multipleDataSource" />
</bean>


<!-- 注解方式配置事物 -->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>

</beans>
3、自定义数据库切换类

public class MultipleDataSource extends AbstractRoutingDataSource {


private static final ThreadLocal<String> dataSourceKey = new InheritableThreadLocal<String>();

public static void setDataSourceKey(String dataSource){
dataSourceKey.set(dataSource);
}

@Override
protected Object determineCurrentLookupKey() {
return dataSourceKey.get();
}

}

4、设置注解

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
@Documented
public @interface DataSwitch {
String dataSource() default "";
}

5、编写AOP类

@Aspect
@Component
public class DataSwitchAop {
//@Pointcut()
//@Pointcut("execution(public * com.changneng.penalize.business.service.impl.*(..))")
public void execute(){
}

@Before("@annotation(com.changneng.penalize.business.aop.DataSwitch)")
public void dataSwitch(JoinPoint joinPoint){
Signature signature = joinPoint.getSignature();

MethodSignature methodSignature =(MethodSignature) signature;
   Method method = methodSignature.getMethod();
   DataSwitch data = null;
   if(method!=null){
    data = method.getAnnotation(DataSwitch.class);
   }
   String dataSource = data.dataSource();
System.out.println("datasource...."+dataSource);
if(dataSource!=null){
MultipleDataSource.setDataSourceKey(dataSource);
}
}
}

6、在哪个需要切换数据库的Service中加上注解例如:

扫描二维码关注公众号,回复: 2631707 查看本文章

//切换数据库
@DataSwitch(dataSource="dateSource_second")
public int getBaseID(String areaCode,String enterPriseID){
//MultipleDataSource.setDataSourceKey("dateSource_second");
return dbUtilMapper.selectBaseID(areaCode,enterPriseID);
}


猜你喜欢

转载自blog.csdn.net/qq_33500630/article/details/78203054