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

在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条)

报告相同问题?

悬赏问题

  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
  • ¥20 Vite 打包的 Vue3 组件库,图标无法显示
  • ¥15 php 同步电商平台多个店铺增量订单和订单状态
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别