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

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

  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. #mysql2 database setting
  8. #jdbc.type=mysql
  9. #jdbc.driver=com.mysql.jdbc.Driver
  10. jdbc.url2=jdbc:mysql://218.28.123.82:3306/stkcentervideosys?useUnicode=true&characterEncoding=utf-8
  11. jdbc.username2=root
  12. jdbc.password2=root

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

第一处(spring-context.xml):

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

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

  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

  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)

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

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

  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很简单

  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. <select id="findList" resultType="StkScenerySpot">
  13. SELECT
  14. <include refid="stkScenerySpotColumns"/>
  15. FROM stk_scenery_spot a
  16. <include refid="stkScenerySpotJoins"/>
  17. <where>
  18. 1 = 1
  19. </where>
  20. <choose>
  21. <otherwise>
  22. ORDER BY a.Spot_Id DESC
  23. </otherwise>
  24. </choose>
  25. </select>
  26. </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添加多数据源的更多相关文章

  1. 死磕Spring源码之AliasRegistry

    死磕Spring源码之AliasRegistry 父子关系 graph TD; AliasRegistry-->BeanDefinitionRegistry; 代码实现 作为bean定义的最顶层 ...

  2. 【死磕jeestie源码】类型后面三个点(String...)和数组(String[])的区别

    类型后面三个点(String...),是从Java 5开始,Java语言对方法参数支持一种新写法,叫可变长度参数列表,其语法就是类型后跟...,表示此处接受的参数为0到多个Object类型的对象,或者 ...

  3. 死磕itchat源码--core.py

    core.py文件中的Core类定义了itchat的所有接口.且,仅仅是定义了接口,全部在component包中实现重构.其用法如下表述: 缺省 源码如下: # -*- encoding: utf-8 ...

  4. 死磕itchat源码--__init__.py

    itchat包中的__init__.py是该库的入口:在该文件中的源码如下: # -*- coding: utf-8 -*- from . import content from .core impo ...

  5. 死磕abstractqueuedsynchronizer源码

    第一次写博客,先练练手. 1.AQS是什么? 在Lock中,用到了一个同步队列AQS,全称为AbstractQueuedSynchronizer,它是一个同步工具也是lock用来实现线程同步的核心组件 ...

  6. 死磕itchat源码--config.py

    itchat的配置文件,源码: import os, platform # 版本及微信的url,二维码等 VERSION = '1.3.10' BASE_URL = 'https://login.we ...

  7. 死磕itchat源码--content.py

    content.py中定义了接受消息的类型,即,用于注册消息函数时的参数类型.源码如下: TEXT = 'Text' MAP = 'Map' CARD = 'Card' NOTE = 'Note' S ...

  8. 死磕itchat源码--目录结构

    阅读itchat源码时,先弄清itchat的目录结构 itchat │ config.py │ content.py │ core.py │ log.py │ returnvalues.py │ ut ...

  9. 死磕Spring源码系列

    一.Spring总体架构 1.架构图 2.SpringIOC:核心容器提供 Spring 框架的基本功能.核心容器的主要组件是 BeanFactory,它是工厂模式的实现.BeanFactory 使用 ...

  10. 一般源码安装添加的GD库 是不支持 jpeg 格式的图片的

    一般源码安装添加的GD库 是不支持 jpeg 格式的图片的,只支持如下格式 GD Support enabled GD Version bundled (2.0.34 compatible) GIF ...

随机推荐

  1. elastic-job 新手指南

    大多数情况下,定时任务我们一般使用quartz开源框架就能满足应用场景.但如果考虑到健壮性等其它一些因素,就需要自己下点工夫,比如:要避免单点故障,至少得部署2个节点吧,但是部署多个节点,又有其它问题 ...

  2. [原创]zabbix工具介绍,安装及使用

    [原创]zabbix工具介绍,安装及使用 http://waringid.blog.51cto.com/65148/955939/

  3. Windows如何安装pip

    下载这个文件:  https://bootstrap.pypa.io/get-pip.py 然后到下载目录执行Python命令:   (管理员权限执行) python get-pip.py

  4. 版本控制-GitHub

    前面几篇文章,我们介绍了Git的基本用法及Git服务器的搭建,本篇文章来学习一下如何使用GitHub.GitHub是开源的代码库以及版本控制库,是目前使用网络上使用最为广泛的服务,GitHub可以托管 ...

  5. 常用CTPN、CRNN文本检测识别框架

    一.SWT识别: yestinsong/Text-Detection( Text Detection System with MSER , SWT and Text Verification(fft ...

  6. android开发之打包签名

    android开发之数字签名 http://www.cnblogs.com/fengzhblog/archive/2013/05/06/3063104.html Android系统要求所有的程序经过数 ...

  7. 阿里云logtail采集IDC机房机器需添加AliUids操作

    Configure AliUids for ECS servers under other Alibaba Cloud accounts or on-premises IDCs If Logtail ...

  8. 最新Android & iOS设计尺寸规范

    Android 和 iPhone.iPad以及主流手机屏幕的分辨率和相关设计尺寸规范 <点击看大图>

  9. SNF快速开发平台3.0之--系统里广播的作用--迅速及时、简明扼要的把信息发送给接收者

    广播信息,即速度快捷.迅速及时.简明扼要的把信息发送给接收者. 当然在SNF快速开发平台上你也可以作为公告使用.不管当做什么使用要满足以下需求: 简单操作:页面操作简单 只需要输入内容就可以发送. 灵 ...

  10. input框触发回车事件

    window.event只能在IE下运行,不能在firefox下运行,这是因为firefox的event只能在事件发生的现场使用.   在firefox里直接调用event对象会报undefined. ...