努力的程序yuan 2016-04-22 09:14 采纳率: 33.3%
浏览 4087
已采纳

在springmvc中如何在service层切换数据源

我现在的思路是在我的application中配置两个数据库
利用aop自动切换数据库

 <bean id="dataSource" class="com.staples.*.DynamicDataSource">
        <property name="targetDataSources">
            <map key-type="java.lang.String">
                <entry key="dataSourceOne" value-ref=" dataSourceOne " />
                <entry key="dataSourceTwo" value-ref=" dataSourceTwo " />
            </map>
        </property>
        <property name="defaultTargetDataSource" ref=" dataSourceOne " />
    </bean>


<bean id="dataSourceInterceptor" class="com.staples.*. DataSourceInterceptor " />

    <aop:config>
        <aop:aspect id="dataSourceAspect" ref="dataSourceInterceptor">
            <aop:pointcut id="dsOracleOne " expression="execution(* com.controller.生产数据的controller.*.*(..))" />
            <aop:pointcut id="dsOracleTwo" expression="execution(*com.service.日志的service.*.*(..))" />
            <aop:before method="setdataSourceOne" pointcut-ref="dsOracleOne"/>
            <aop:before method="setdataSourceTwo" pointcut-ref=" dsOracleTwo "/>
        </aop:aspect>
    </aop:config>

下面是我的数据库切换方法

 DynamicDataSource.Java

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

public class DynamicDataSource extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        return DatabaseContextHolder.getCustomerType();
    }
}





DataSourceInterceptor.java

import org.aspectj.lang.JoinPoint;

public class DataSourceInterceptor {

    public void setdataSourceMysql(JoinPoint jp) {
        DatabaseContextHolder.setCustomerType("dataSourceOne");
    }

    public void setdataSourceOracle(JoinPoint jp) {
        DatabaseContextHolder.setCustomerType("dataSourceTwo");
    }
}


DatabaseContextHolder.java

public class DatabaseContextHolder {

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

    public static void setCustomerType(String customerType) {
        contextHolder.set(customerType);
    }

    public static String getCustomerType() {
        return contextHolder.get();
    }

    public static void clearCustomerType() {
        contextHolder.remove();
    }
}

请问我可不可以这样写我的aop啊
我是为了实现日志和生产的数据源分离,而我在保存日志的时候都是直接在事务层调我日志的service,这样可以实现吗

  • 写回答

7条回答 默认 最新

  • CodeManBill 2016-04-22 09:19
    关注

    我给你说个思路吧 你先让一个数据源默认,然后根据请求的信息判断要切换的数据源就行了 你这个配置其实就是按照我说的这样的配置的 是可行的!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 latex投稿显示click download
  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?