zoukankan      html  css  js  c++  java
  • ssm多数据源配置

    1.在.properties配置文件中 添加第二个数据源信息(type2,driver2,
      url2,username2,pawwword2)

    2.修改spring-context.xml(src/main/resources/),有3处需要修改/添加
    第一处,添加bean id="dataSource2"

    第二处(spring-context.xml):修改为sqlSessionFactory bean,将dataSource改为dynamicDataSource

    第三处 (spring-context.xml):修改为transactionManager bean
      同第二处一样 将ref="dataSource" 改为ref="dynamicDataSource"
      并添加 dynamicDataSource bean

    3.添加DynamicDataSource.java

    package com.thinkgem.wlw.common.db;
    
    import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
    
    /**
     * 数据源切换方法类
     * @author zhouhe
     * @version 2018-11-7
     */
    public class DynamicDataSource extends AbstractRoutingDataSource {
        private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
    
    
        public static String getCurrentLookupKey() {
            return (String) contextHolder.get();
        }
    
    
        /**
         * 设置线程的数据源
         * @param currentLookupKey
         */
        public static void setCurrentLookupKey(String currentLookupKey) {
            contextHolder.set(currentLookupKey);
        }
    
        @Override
        protected Object determineCurrentLookupKey() {
            return getCurrentLookupKey();
        }
    }


    4.在Controller中控制数据源

     在Controller中方法的开头用  DynamicDataSource.setCurrentLookupKey("dataSource2"); 来切换数据数据源,

    这里要注意的是方法结束的时候要把数据源切换回来 DynamicDataSource.setCurrentLookupKey("dataSource");

    否则会有问题。

    注:这里说一下在jeesite中使用的话要有一点需要注意,就是在修改删除方法中切换数据源的话要在

    Controller中的get();方法中加上 DynamicDataSource.setCurrentLookupKey("dataSource2");  因为在

    执行修改,删除方法之前会先执行此方法。

    这里要注意,切换数据源不能放到事务里面,否则会导致无法切换

    还有一个问题,这里的数据源切换可能会出现数据库连接超时timeout现象,需要设置如下:

    一:数据库连接加上 autoReconnect=true;(当数据库连接异常中断时,是否自动重新连接?)

    二:mysql中my.ini文件添加(这里设置完需要重启mysql)

    wait_timeout=31536000
    interactive_timeout=31536000
  • 相关阅读:
    Jquery 跨域请求JSON数据问题
    js定时器实现图片轮播
    Redis数据一致性
    Redis缓存击穿、缓存穿透、缓存雪崩
    数据库连接池druid连接mysql数据库‘链路断开’问题
    Mysql启动错误: Can’t create test file xxx lower-test
    DB2-表空间
    DB2-Schema
    DB2-数据库
    DB2-实例
  • 原文地址:https://www.cnblogs.com/zhouheblog/p/9920884.html
Copyright © 2011-2022 走看看