spring jdbcTemplate多数据源简单实用

第一、config/jdbc.properties
# HC本地数据库
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/hcdatabase?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
jdbc.username=root
jdbc.password=root

# 模拟全量特征集数据来源
jdbc.other.driver=com.mysql.jdbc.Driver
jdbc.other.url=jdbc:mysql://localhost:3306/imooc?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
jdbc.other.username=root
jdbc.other.password=root

第二、config/applicationContext-datasource.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
    http://www.springframework.org/schema/tx   
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-3.0.xsd  
    http://www.springframework.org/schema/aop  
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <!-- 数据库连接配置信息 -->
    <context:property-placeholder location="classpath:/config/jdbc.properties" />
    
    <!-- hc数据源配置 -->
    <bean id="source_hc" class="org.apache.commons.dbcp.BasicDataSource"
        p:driverClassName="${jdbc.driver}" p:url="${jdbc.url}" p:username="${jdbc.username}"
        p:password="${jdbc.password}" p:maxIdle="50" p:maxActive="10"
        p:maxWait="3000" p:minIdle="3" p:removeAbandoned="true"
        p:removeAbandonedTimeout="36000" p:testOnBorrow="true" p:testOnReturn="true"
        p:testWhileIdle="true" />
    <!-- 动态配置数据源 -->
    <bean id="dataSource" class="com.talkweb.huicai.datasource.DynamicDataSource">
        <property name="targetDataSources">
            <map key-type="java.lang.String">
                <entry value-ref="source_hc" key="source_hc"></entry>
            </map>
        </property>
        <property name="defaultTargetDataSource" ref="source_hc"></property>      <!-- 默认使用ds1的数据源 -->
    </bean>
    
    <!-- 配置 spring 的 jdbcTemplate -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" p:dataSource-ref="dataSource" />
    <!-- 事务管理器 -->
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource" />
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="delete*" propagation="REQUIRED" read-only="false" />
            <tx:method name="insert*" propagation="REQUIRED" read-only="false" />
            <tx:method name="save*" propagation="REQUIRED" read-only="false" />
            <tx:method name="update*" propagation="REQUIRED" read-only="false" />
            <tx:method name="query*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="select*" propagation="SUPPORTS" read-only="true" />
        </tx:attributes>
    </tx:advice>

    <!-- otherDataSource全量特征集来源库-->
    <bean id="source_other" class="org.apache.commons.dbcp.BasicDataSource"
                p:driverClassName="${jdbc.other.driver}" p:url="${jdbc.other.url}" p:username="${jdbc.other.username}"
                p:password="${jdbc.other.password}" p:maxIdle="50" p:maxActive="10"
                p:maxWait="3000" p:minIdle="3" p:removeAbandoned="true"
                p:removeAbandonedTimeout="36000" p:testOnBorrow="true" p:testOnReturn="true"
                p:testWhileIdle="true" />
    <!-- otherDataSource动态配置数据源 -->
    <bean id="otherDataSource" class="com.talkweb.huicai.datasource.DynamicDataSource">
        <property name="targetDataSources">
            <map key-type="java.lang.String">
                <entry value-ref="source_other" key="source_other"></entry>
            </map>
        </property>
        <property name="defaultTargetDataSource" ref="source_other"></property>      <!-- 默认使用ds1的数据源 -->
    </bean>
    <!-- othertransactionManager事务管理器 -->
    <bean name="othertransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="otherDataSource" />
    <!-- 配置 spring 的 otherJdbcTemplate -->
    <bean id="otherJdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" p:dataSource-ref="otherDataSource"/>
    <tx:advice id="otherTxAdvice" transaction-manager="othertransactionManager">
        <tx:attributes>
            <tx:method name="delete*" propagation="REQUIRED" read-only="false" />
            <tx:method name="insert*" propagation="REQUIRED" read-only="false" />
            <tx:method name="save*" propagation="REQUIRED" read-only="false" />
            <tx:method name="update*" propagation="REQUIRED" read-only="false" />
            <tx:method name="query*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="select*" propagation="SUPPORTS" read-only="true" />
        </tx:attributes>
    </tx:advice>
    
    <!-- 配置session工厂 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
                p:dataSource-ref="dataSource" p:configLocation="classpath:/config/mybatis.xml"
                p:mapperLocations="classpath:com/talkweb/huicai/dao/*.xml">
        <property name="typeHandlersPackage" value="com.talkweb.huicai.common" />
    </bean>
    
    <!-- 自动扫描所有的mapper接口 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
                p:basePackage="com.talkweb.huicai.mapper" p:sqlSessionFactoryBeanName="sqlSessionFactory" />
    
    <!-- 切入点 -->
    <aop:config proxy-target-class="true">
        <aop:pointcut id="pc"
            expression="execution(public * com.talkweb.huicai.service.*.*(..))" />
        <aop:advisor pointcut-ref="pc" advice-ref="txAdvice" />
        <aop:advisor pointcut-ref="pc" advice-ref="otherTxAdvice" />
    </aop:config>
</beans>
第三、后台使用方式
   //获取jdbcTemplate
    public final ApplicationContext ctx = new ClassPathXmlApplicationContext("/config/applicationContext-datasource.xml");
    public final JdbcTemplate jdbcTemplate = (JdbcTemplate) ctx.getBean("otherJdbcTemplate");
    
      /**
     * 生成 种子用户与候选用户文件
     * @param sceneInfo
     * @param taskInfo
     * @return
     */
    public TaskInfo createUserFile(SceneInfo sceneInfo,TaskInfo taskInfo) throws Exception{
        for(int i = 0; i < 2; i++){
            //生成文件路径
            String pathType = i==0 ? "seedFilePath" : "candFilePath" ;
            String fileType = i==0 ? "hc_seed_" : "hc_cand_";
            String path = localBasePath + File.separator + "datafiles" + File.separator + "file" + taskInfo.gettId() + propertyUtil.getProperty(pathType).replace("/", File.separator);
            String fileName= fileType +taskInfo.gettId()+".txt";
            //获取用户文件
            File userFile = new File((path+fileName));
            //如果用户父文件夹不存在,就创建文件夹与文件
            File userFileP = new File(path);
            boolean newLineFlag = true;
            if (!userFileP.exists()){
                userFileP.mkdirs();
                userFile = new File(path,fileName);
                newLineFlag = false;
            }
            //写入全量特征集
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(userFile, true)));
            //生成sql
            String sql = "select user_id from "+sceneInfo.getSeedInterfaceTable();
            //jdbcTemplate执行sql
            SqlRowSet result = jdbcTemplate.queryForRowSet(sql);
            //生成文件内容
            while(result.next()){
                if(i != 0 || newLineFlag){
                    bw.newLine();
                }
                bw.write(result.getString("user_id"));
            }
            //taskInfo赋值用户文件路径
            taskInfoUserPath(taskInfo, i, path, fileName, userFileP);
        }
        return taskInfo;
    }
 

转载于:https://my.oschina.net/dreambreeze/blog/1620409

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值