【死磕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