【死磕jeesite源码】jeesite添加多数据源

本文转载自jeesite添加多数据源

1.jeesite.properties 添加数据源信息,(url2,username2,pawwword2)

Java代码  收藏代码
  1. #mysql database setting  
  2. jdbc.type=mysql  
  3. jdbc.driver=com.mysql.jdbc.Driver  
  4. jdbc.url=jdbc:mysql://localhost:3306/website?useUnicode=true&characterEncoding=utf-8  
  5. jdbc.username=root  
  6. jdbc.password=root  
  7.    
  8. #mysql2 database setting  
  9. #jdbc.type=mysql  
  10. #jdbc.driver=com.mysql.jdbc.Driver  
  11. jdbc.url2=jdbc:mysql://218.28.123.82:3306/stkcentervideosys?useUnicode=true&characterEncoding=utf-8  
  12. jdbc.username2=root  
  13. jdbc.password2=root  


2.修改spring-context.xml(src/main/resources/),3处需要修改/添加

第一处(spring-context.xml):

Java代码  收藏代码
  1. <!-- 第一个数据源配置, 使用 BoneCP 数据库连接池 -->  
  2.     <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">   
  3.         <!-- 数据源驱动类可不写,Druid默认会自动根据URL识别DriverClass -->  
  4.         <property name="driverClassName" value="${jdbc.driver}" />  
  5.            
  6.         <!-- 基本属性 url、user、password -->  
  7.         <property name="url" value="${jdbc.url}" />  
  8.         <property name="username" value="${jdbc.username}" />  
  9.         <property name="password" value="${jdbc.password}" />  
  10.            
  11.         <!-- 配置初始化大小、最小、最大 -->  
  12.         <property name="initialSize" value="${jdbc.pool.init}" />  
  13.         <property name="minIdle" value="${jdbc.pool.minIdle}" />   
  14.         <property name="maxActive" value="${jdbc.pool.maxActive}" />  
  15.            
  16.         <!-- 配置获取连接等待超时的时间 -->  
  17.         <property name="maxWait" value="60000" />  
  18.            
  19.         <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->  
  20.         <property name="timeBetweenEvictionRunsMillis" value="60000" />  
  21.            
  22.         <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->  
  23.         <property name="minEvictableIdleTimeMillis" value="300000" />  
  24.            
  25.         <property name="validationQuery" value="${jdbc.testSql}" />  
  26.         <property name="testWhileIdle" value="true" />  
  27.         <property name="testOnBorrow" value="false" />  
  28.         <property name="testOnReturn" value="false" />  
  29.            
  30.         <!-- 打开PSCache,并且指定每个连接上PSCache的大小(Oracle使用)  
  31.         <property name="poolPreparedStatements" value="true" />  
  32.         <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> -->  
  33.            
  34.         <!-- 配置监控统计拦截的filters -->  
  35.         <property name="filters" value="stat" />   
  36.     </bean>  
  37.     <!-- 第二个数据源配置, 使用 BoneCP 数据库连接池 -->  
  38.     <bean id="dataSource2" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">   
  39.         <!-- 数据源驱动类可不写,Druid默认会自动根据URL识别DriverClass -->  
  40.         <property name="driverClassName" value="${jdbc.driver}" />  
  41.            
  42.         <!-- 基本属性 url、user、password -->  
  43.         <property name="url" value="${jdbc.url2}" />  
  44.         <property name="username" value="${jdbc.username2}" />  
  45.         <property name="password" value="${jdbc.password2}" />  
  46.            
  47.         <!-- 配置初始化大小、最小、最大 -->  
  48.         <property name="initialSize" value="${jdbc.pool.init}" />  
  49.         <property name="minIdle" value="${jdbc.pool.minIdle}" />   
  50.         <property name="maxActive" value="${jdbc.pool.maxActive}" />  
  51.            
  52.         <!-- 配置获取连接等待超时的时间 -->  
  53.         <property name="maxWait" value="60000" />  
  54.            
  55.         <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->  
  56.         <property name="timeBetweenEvictionRunsMillis" value="60000" />  
  57.            
  58.         <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->  
  59.         <property name="minEvictableIdleTimeMillis" value="300000" />  
  60.            
  61.         <property name="validationQuery" value="${jdbc.testSql}" />  
  62.         <property name="testWhileIdle" value="true" />  
  63.         <property name="testOnBorrow" value="false" />  
  64.         <property name="testOnReturn" value="false" />  
  65.            
  66.         <!-- 打开PSCache,并且指定每个连接上PSCache的大小(Oracle使用)  
  67.         <property name="poolPreparedStatements" value="true" />  
  68.         <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> -->  
  69.            
  70.         <!-- 配置监控统计拦截的filters -->  
  71.         <property name="filters" value="stat" />   
  72.     </bean>  
  73.     <!-- 动态数据源 -->  
  74.     <bean id="dynamicDataSource" class="com.thinkgem.jeesite.common.db.DynamicDataSource">  
  75.         <property name="defaultTargetDataSource" ref="dataSource"/>  
  76.         <property name="targetDataSources">  
  77.             <map>  
  78.                 <entry key="dataSource" value-ref="dataSource"/>  
  79.                 <entry key="dataSource2" value-ref="dataSource2"/>  
  80.             </map>  
  81.         </property>  
  82.     </bean>  


第二处(spring-context.xml):修改为dynamicDataSource

Java代码  收藏代码
  1. <!-- MyBatis begin  -->  
  2.     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  3.         <property name="dataSource" ref="dynamicDataSource"/>  
  4.         <property name="typeAliasesPackage" value="com.thinkgem.jeesite"/>  
  5.         <property name="typeAliasesSuperType" value="com.thinkgem.jeesite.common.persistence.BaseEntity"/>  
  6.         <property name="mapperLocations" value="classpath:/mappings/**/*.xml"/>  
  7.         <property name="configLocation" value="classpath:/mybatis-config.xml"></property>  
  8.     </bean>  



第三处(spring-context.xml):修改为dynamicDataSource

Java代码  收藏代码
  1. <!-- 定义事务 -->  
  2. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  3.     <property name="dataSource" ref="dynamicDataSource" />  
  4. </bean>  


3.添加DynamicDataSource.java (com.thinkgem.jeesite.common.db.DynamicDataSource.java)

Java代码  收藏代码
  1. package com.thinkgem.jeesite.common.db;  
  2.    
  3. import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;  
  4.    
  5. /** 
  6.  * Mysql 多数据源切换 
  7.  * 
  8.  * @author sa 
  9.  * @version V1.0 
  10.  * @Description: 
  11.  * @date 2015/10/09 
  12.  */  
  13. public class DynamicDataSource extends AbstractRoutingDataSource {  
  14.     private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();    
  15.          
  16.     /**  
  17.      *   
  18.      * @author sa  
  19.      * @date 2012-5-18 下午4:06:44  
  20.      * @return the currentLookupKey  
  21.      */    
  22.     public static String getCurrentLookupKey() {    
  23.         return (String) contextHolder.get();    
  24.     }    
  25.      
  26.     /**  
  27.      *   
  28.      * @author sa  
  29.      * @date 2012-5-18 下午4:06:44  
  30.      * @param currentLookupKey  
  31.      *            the currentLookupKey to set  
  32.      */    
  33.     public static void setCurrentLookupKey(String currentLookupKey) {    
  34.         contextHolder.set(currentLookupKey);    
  35.     }    
  36.      
  37.     /*  
  38.      * (non-Javadoc)  
  39.      *   
  40.      * @see  
  41.      * org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource#  
  42.      * determineCurrentLookupKey()  
  43.      */    
  44.     @Override    
  45.     protected Object determineCurrentLookupKey() {    
  46.         return getCurrentLookupKey();    
  47.     }    
  48. }  



4.在Controller中切换(在service层切换不管用,还没查原因)

Java代码  收藏代码
  1. //切换数据源dataSource2,默认数据源dataSource  
  2.         DynamicDataSource.setCurrentLookupKey("dataSource2");  
  3.         List list = stkScenerySpotService.findAll();  
  4.         model.addAttribute("list",list);  
  5.         DynamicDataSource.setCurrentLookupKey("dataSource");  

5.在定时任务中切换数据源

@Service
@Lazy(false)
public class ImportGamexxjh5 {
    private static Logger logger = LoggerFactory.getLogger(ImportGamexxjh5.class);
    @Autowired
    Gamexxjh5Service gamexxjh5Service;
    @Autowired
    TfAnaysisResultTyhxService tfAnaysisResultTyhxService;

    @Scheduled(cron = "0 20 18 * * ?")
    public void importGameXXJH5() {
        logger.info("-------执行importGameXXJH5开始------->"+ DateUtils.getDateTime());
        SimpleDateFormat myFmt = new SimpleDateFormat("yyMMdd");
        Date date = new Date();
        String nowdate = myFmt.format(date);
        String tablename="order_"+nowdate;
        rundata(tablename);
        logger.info("-------导入H5数据库中"+tablename+"表的渠道汇总数据----");
        logger.info("-------执行importGameXXJH5结束------->"+DateUtils.getDateTime());

    }

    public void rundata(String tablename) {

        //数据源切至H5数据库,获取按渠道按天汇总数据
        DynamicDataSource.setCurrentLookupKey("h5_dataSource");
        List<Gamexxjh5> gList = gamexxjh5Service.queryAll(tablename);
        //数据源切换回至版权数据库
        DynamicDataSource.setCurrentLookupKey("dataSource");
        //将数据导入至版权的数据表中

        for (Gamexxjh5 item : gList) {
            TfAnaysisResultTyhx tfAnaysisResultTyhx =new TfAnaysisResultTyhx();
            tfAnaysisResultTyhx.setChannelid(item.getChannelid());
            tfAnaysisResultTyhx.setChannelname(item.getChannelname());
            tfAnaysisResultTyhx.setDaypayment(item.getDaypayment());
            tfAnaysisResultTyhx.setStatdate(item.getStatdate());

            tfAnaysisResultTyhx.setGameid("41");
            tfAnaysisResultTyhx.setGamename("新仙剑H5");
            tfAnaysisResultTyhx.setGameEnglishName("xinxianjianH5");
            tfAnaysisResultTyhx.setResult("Y");
            tfAnaysisResultTyhx.setChanneltype("");
            tfAnaysisResultTyhx.setIpowner("大宇资讯股份有限公司");
            tfAnaysisResultTyhx.setIpownerid("8");
            tfAnaysisResultTyhx.setMoneycl(item.getDaypayment());
            tfAnaysisResultTyhx.setMoney(item.getDaypayment());
            tfAnaysisResultTyhxService.save(tfAnaysisResultTyhx);
        }
    }


}

 
注:

要对切换的数据源dataSource2 中的表手动写映射和三层
实体:com.thinkgem.jeesite.modules.cms.entity.StkScenerySpot.java
service:com.thinkgem.jeesite.modules.cms.service.StkScenerySpotService.java
mapper:StkScenerySpotDao.xml (src/main/resources/modules/cms)

我只查所有,所以sql很简单

Java代码 
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  3. <mapper namespace="com.thinkgem.jeesite.modules.cms.dao.StkScenerySpotDao">  
  4.     <sql id="stkScenerySpotColumns">  
  5.         a.Spot_Id AS "id",  
  6.         a.CamId AS "camId",  
  7.         a.Name AS "name",  
  8.         a.Comment AS "commnet"  
  9.     </sql>  
  10.     <sql id="stkScenerySpotJoins">  
  11.     </sql>  
  12.        
  13.     <select id="findList" resultType="StkScenerySpot">  
  14.         SELECT   
  15.             <include refid="stkScenerySpotColumns"/>  
  16.         FROM stk_scenery_spot a  
  17.         <include refid="stkScenerySpotJoins"/>  
  18.         <where>  
  19.             1 = 1   
  20.         </where>  
  21.         <choose>  
  22.                
  23.             <otherwise>  
  24.                 ORDER BY a.Spot_Id DESC  
  25.             </otherwise>  
  26.         </choose>  
  27.     </select>  
  28. </mapper>  

六、jeesite如何跨库查询

jeesite.propertity中配置的数据源会设置一个数据库,这个数据库只是启动库。

在mapper.xml中可以可以跨库查询

jdbc.type=mysql
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://106.75.21.XX:3306/copyright?useUnicode=true&characterEncoding=utf-8
jdbc.username=name1
jdbc.password=password1
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.thinkgem.jeesite.modules.gamexxjh5.dao.Gamexxjh5Dao">
    <select id="queryAll" resultType="Gamexxjh5">
        select  t.statdate,t.channelid,a.channelname,t.daypayment
        from (
            select from_unixtime(createTime,'%Y-%m-%d')  as statdate,channelid,sum(paymoney)/100 as daypayment
            from h5game_shengli_com_xxjqxz.${tablename}   where chargeStatus='2'
            group by  from_unixtime(createTime,'%Y-%m-%d') ,channelid
            order by  from_unixtime(createTime,'%Y-%m-%d')  desc
        ) t
        left join h5game_shengli_com.channel a on a.id=t.channelid
    </select>
</mapper>


效果:
jeesite数据库表


datasource2数据表


获取数据


前端展示


datasource2数据表中的内容


参考资料:http://www.hifreud.com/2015/02/25/07-spring-datasources/
http://www.cnblogs.com/digdeep/p/4512368.html

原文地址:https://www.cnblogs.com/abc8023/p/9099047.html