【死磕jeesite源码】jeesite添加多数据源
本文转载自jeesite添加多数据源
1.jeesite.properties 添加数据源信息,(url2,username2,pawwword2)
- #mysql database setting
- jdbc.type=mysql
- jdbc.driver=com.mysql.jdbc.Driver
- jdbc.url=jdbc:mysql://localhost:3306/website?useUnicode=true&characterEncoding=utf-8
- jdbc.username=root
- jdbc.password=root
- #mysql2 database setting
- #jdbc.type=mysql
- #jdbc.driver=com.mysql.jdbc.Driver
- jdbc.url2=jdbc:mysql://218.28.123.82:3306/stkcentervideosys?useUnicode=true&characterEncoding=utf-8
- jdbc.username2=root
- jdbc.password2=root
2.修改spring-context.xml(src/main/resources/),3处需要修改/添加
第一处(spring-context.xml):
- <!-- 第一个数据源配置, 使用 BoneCP 数据库连接池 -->
- <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
- <!-- 数据源驱动类可不写,Druid默认会自动根据URL识别DriverClass -->
- <property name="driverClassName" value="${jdbc.driver}" />
- <!-- 基本属性 url、user、password -->
- <property name="url" value="${jdbc.url}" />
- <property name="username" value="${jdbc.username}" />
- <property name="password" value="${jdbc.password}" />
- <!-- 配置初始化大小、最小、最大 -->
- <property name="initialSize" value="${jdbc.pool.init}" />
- <property name="minIdle" value="${jdbc.pool.minIdle}" />
- <property name="maxActive" value="${jdbc.pool.maxActive}" />
- <!-- 配置获取连接等待超时的时间 -->
- <property name="maxWait" value="60000" />
- <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
- <property name="timeBetweenEvictionRunsMillis" value="60000" />
- <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
- <property name="minEvictableIdleTimeMillis" value="300000" />
- <property name="validationQuery" value="${jdbc.testSql}" />
- <property name="testWhileIdle" value="true" />
- <property name="testOnBorrow" value="false" />
- <property name="testOnReturn" value="false" />
- <!-- 打开PSCache,并且指定每个连接上PSCache的大小(Oracle使用)
- <property name="poolPreparedStatements" value="true" />
- <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> -->
- <!-- 配置监控统计拦截的filters -->
- <property name="filters" value="stat" />
- </bean>
- <!-- 第二个数据源配置, 使用 BoneCP 数据库连接池 -->
- <bean id="dataSource2" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
- <!-- 数据源驱动类可不写,Druid默认会自动根据URL识别DriverClass -->
- <property name="driverClassName" value="${jdbc.driver}" />
- <!-- 基本属性 url、user、password -->
- <property name="url" value="${jdbc.url2}" />
- <property name="username" value="${jdbc.username2}" />
- <property name="password" value="${jdbc.password2}" />
- <!-- 配置初始化大小、最小、最大 -->
- <property name="initialSize" value="${jdbc.pool.init}" />
- <property name="minIdle" value="${jdbc.pool.minIdle}" />
- <property name="maxActive" value="${jdbc.pool.maxActive}" />
- <!-- 配置获取连接等待超时的时间 -->
- <property name="maxWait" value="60000" />
- <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
- <property name="timeBetweenEvictionRunsMillis" value="60000" />
- <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
- <property name="minEvictableIdleTimeMillis" value="300000" />
- <property name="validationQuery" value="${jdbc.testSql}" />
- <property name="testWhileIdle" value="true" />
- <property name="testOnBorrow" value="false" />
- <property name="testOnReturn" value="false" />
- <!-- 打开PSCache,并且指定每个连接上PSCache的大小(Oracle使用)
- <property name="poolPreparedStatements" value="true" />
- <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> -->
- <!-- 配置监控统计拦截的filters -->
- <property name="filters" value="stat" />
- </bean>
- <!-- 动态数据源 -->
- <bean id="dynamicDataSource" class="com.thinkgem.jeesite.common.db.DynamicDataSource">
- <property name="defaultTargetDataSource" ref="dataSource"/>
- <property name="targetDataSources">
- <map>
- <entry key="dataSource" value-ref="dataSource"/>
- <entry key="dataSource2" value-ref="dataSource2"/>
- </map>
- </property>
- </bean>
第二处(spring-context.xml):修改为dynamicDataSource
- <!-- MyBatis begin -->
- <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
- <property name="dataSource" ref="dynamicDataSource"/>
- <property name="typeAliasesPackage" value="com.thinkgem.jeesite"/>
- <property name="typeAliasesSuperType" value="com.thinkgem.jeesite.common.persistence.BaseEntity"/>
- <property name="mapperLocations" value="classpath:/mappings/**/*.xml"/>
- <property name="configLocation" value="classpath:/mybatis-config.xml"></property>
- </bean>
第三处(spring-context.xml):修改为dynamicDataSource
- <!-- 定义事务 -->
- <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource" ref="dynamicDataSource" />
- </bean>
3.添加DynamicDataSource.java (com.thinkgem.jeesite.common.db.DynamicDataSource.java)
- package com.thinkgem.jeesite.common.db;
- import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
- /**
- * Mysql 多数据源切换
- *
- * @author sa
- * @version V1.0
- * @Description:
- * @date 2015/10/09
- */
- public class DynamicDataSource extends AbstractRoutingDataSource {
- private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
- /**
- *
- * @author sa
- * @date 2012-5-18 下午4:06:44
- * @return the currentLookupKey
- */
- public static String getCurrentLookupKey() {
- return (String) contextHolder.get();
- }
- /**
- *
- * @author sa
- * @date 2012-5-18 下午4:06:44
- * @param currentLookupKey
- * the currentLookupKey to set
- */
- public static void setCurrentLookupKey(String currentLookupKey) {
- contextHolder.set(currentLookupKey);
- }
- /*
- * (non-Javadoc)
- *
- * @see
- * org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource#
- * determineCurrentLookupKey()
- */
- @Override
- protected Object determineCurrentLookupKey() {
- return getCurrentLookupKey();
- }
- }
4.在Controller中切换(在service层切换不管用,还没查原因)
- //切换数据源dataSource2,默认数据源dataSource
- DynamicDataSource.setCurrentLookupKey("dataSource2");
- List list = stkScenerySpotService.findAll();
- model.addAttribute("list",list);
- 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很简单
- <?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.cms.dao.StkScenerySpotDao">
- <sql id="stkScenerySpotColumns">
- a.Spot_Id AS "id",
- a.CamId AS "camId",
- a.Name AS "name",
- a.Comment AS "commnet"
- </sql>
- <sql id="stkScenerySpotJoins">
- </sql>
- <select id="findList" resultType="StkScenerySpot">
- SELECT
- <include refid="stkScenerySpotColumns"/>
- FROM stk_scenery_spot a
- <include refid="stkScenerySpotJoins"/>
- <where>
- 1 = 1
- </where>
- <choose>
- <otherwise>
- ORDER BY a.Spot_Id DESC
- </otherwise>
- </choose>
- </select>
- </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
【死磕jeesite源码】jeesite添加多数据源的更多相关文章
- 死磕Spring源码之AliasRegistry
死磕Spring源码之AliasRegistry 父子关系 graph TD; AliasRegistry-->BeanDefinitionRegistry; 代码实现 作为bean定义的最顶层 ...
- 【死磕jeestie源码】类型后面三个点(String...)和数组(String[])的区别
类型后面三个点(String...),是从Java 5开始,Java语言对方法参数支持一种新写法,叫可变长度参数列表,其语法就是类型后跟...,表示此处接受的参数为0到多个Object类型的对象,或者 ...
- 死磕itchat源码--core.py
core.py文件中的Core类定义了itchat的所有接口.且,仅仅是定义了接口,全部在component包中实现重构.其用法如下表述: 缺省 源码如下: # -*- encoding: utf-8 ...
- 死磕itchat源码--__init__.py
itchat包中的__init__.py是该库的入口:在该文件中的源码如下: # -*- coding: utf-8 -*- from . import content from .core impo ...
- 死磕abstractqueuedsynchronizer源码
第一次写博客,先练练手. 1.AQS是什么? 在Lock中,用到了一个同步队列AQS,全称为AbstractQueuedSynchronizer,它是一个同步工具也是lock用来实现线程同步的核心组件 ...
- 死磕itchat源码--config.py
itchat的配置文件,源码: import os, platform # 版本及微信的url,二维码等 VERSION = '1.3.10' BASE_URL = 'https://login.we ...
- 死磕itchat源码--content.py
content.py中定义了接受消息的类型,即,用于注册消息函数时的参数类型.源码如下: TEXT = 'Text' MAP = 'Map' CARD = 'Card' NOTE = 'Note' S ...
- 死磕itchat源码--目录结构
阅读itchat源码时,先弄清itchat的目录结构 itchat │ config.py │ content.py │ core.py │ log.py │ returnvalues.py │ ut ...
- 死磕Spring源码系列
一.Spring总体架构 1.架构图 2.SpringIOC:核心容器提供 Spring 框架的基本功能.核心容器的主要组件是 BeanFactory,它是工厂模式的实现.BeanFactory 使用 ...
- 一般源码安装添加的GD库 是不支持 jpeg 格式的图片的
一般源码安装添加的GD库 是不支持 jpeg 格式的图片的,只支持如下格式 GD Support enabled GD Version bundled (2.0.34 compatible) GIF ...
随机推荐
- [Beego模型] 六、事务处理
[Beego模型] 一.ORM 使用方法 [Beego模型] 二.CRUD 操作 [Beego模型] 三.高级查询 [Beego模型] 四.使用SQL语句进行查询 [Beego模型] 五.构造查询 [ ...
- Iowait的成因、对系统影响及对策--systemtap
http://blog.csdn.net/yunlianglinfeng/article/details/51698607
- Github如何回退/回滚到某个版本
当然你可以直接在命令行使用 git reset --hard <commit ID号> 或者 git reset --hard HEAD^来进行回退
- Unity Alpha融合参数(便查)
Alpha Blending,中文译作Alpha混合 Blending就是控制透明的.处于光栅化的最后阶段. 这里例如我们给一个模型贴一个材质,那么在某个点计算出来颜色值称为源,而该点之前累积的颜色值 ...
- Java access to the Domino Objects, Part 1
From: https://www.ibm.com/developerworks/lotus/library/ls-Java_access_pt1/index.html Overview Java a ...
- PC高级语言与施耐德、罗克韦尔、台达等PLC的Modbus通讯源代码(ModbusTCP.DLL/ModbusRTU.DLL)
1.0 通讯组件概述 该类通讯组件适用于基于PC高级语言的工业自动化控制系统,用于PC与可编程控制器(PLC).智能仪表等进行数据通讯.组件采用动态链接库文件(*.DLL)的形式,在PC系统的项目工 ...
- eclipse:报错信息The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path
JavaWeb: 报错信息The superclass "javax.servlet.http.HttpServlet" was not found on the Java Bui ...
- 如何修改mac的root密码
mac如果密码忘了,可以同过几个命令重置root密码.前提是你有执行sudo权限的用户: jackdeMacBook-Air:~ jack$ sudo bash jackdeMacBook-Air:~ ...
- linux每日命令(21):find命令之exec
find是我们很常用的一个Linux命令,但是我们一般查找出来的并不仅仅是看看而已,还会有进一步的操作,这个时候exec的作用就显现出来了. 一. exec参数说明: -exec 参数后面跟的是com ...
- 【被C折腾系列】用C调DIOCP编码客户端通信
前几天有个朋友,说他们公司做手游,服务端用的DIOCP3里面做文件服务器,客户端用cocos-x,在调试与diocp通信时老是失败! 于是,我下载了一个Codeblocks经过几个小时的折腾,终于折腾 ...