努力的程序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条)

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值