redis多个数据源配置

转载自:http://blog.csdn.net/weinichendian/article/details/51253506


1、spring-context.xml文件

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"  
  5.     xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"  
  6.     xmlns:p="http://www.springframework.org/schema/p"  
  7.     xsi:schemaLocation="  
  8.         http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd  
  9.         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd  
  10.         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
  11.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
  12.         http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd  
  13.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">  
  14.   
  15.     <!-- 数据同步的数据源配置 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">   
  16.         <property name="driverClass" value="com.mysql.jdbc.Driver" /> <property name="jdbcUrl"   
  17.         value="jdbc:mysql://IP:3306/amb_car_accessory?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true"   
  18.         /> <property name="user" value="" /> <property name="password" value=""   
  19.         /> <property name="minPoolSize" value="1" /> <property name="maxPoolSize"   
  20.         value="30" /> <property name="maxIdleTime" value="1800" /> <property name="acquireIncrement"   
  21.         value="2" /> <property name="maxStatements" value="100" /> <property name="initialPoolSize"   
  22.         value="2" /> <property name="idleConnectionTestPeriod" value="1800" /> <property   
  23.         name="acquireRetryAttempts" value="30" /> <property name="acquireRetryDelay"   
  24.         value="100" /> <property name="breakAfterAcquireFailure" value="false" />   
  25.         <property name="testConnectionOnCheckout" value="true" /> </bean> -->  
  26.     <!-- 多数据源配置使用开始 -->  
  27.     <bean id="dataSourceDefault" class="com.alibaba.druid.pool.DruidDataSource"  
  28.         init-method="init" destroy-method="close">  
  29.         <property name="driverClassName" value="com.mysql.jdbc.Driver" />  
  30.         <property name="url"  
  31.             value="jdbc:mysql://IP:8066/amb_admin?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true" />  
  32.         <property name="username" value="" />  
  33.         <property name="password" value="" />  
  34.         <property name="maxActive" value="20" /><!-- 连接池最大使用连接数 -->  
  35.         <property name="initialSize" value="1" /><!-- 初始化连接大小 -->  
  36.         <property name="maxWait" value="60000" /><!-- 获取连接最大等待时间 -->  
  37.         <property name="minIdle" value="3" /><!-- 连接池最小空闲 -->  
  38.         <property name="removeAbandoned" value="true" /><!-- 自动清除无用连接 -->  
  39.         <property name="removeAbandonedTimeout" value="1800" /><!-- 清除无用连接的等待时间 -->  
  40.         <property name="connectionProperties" value="clientEncoding=UTF-8" /><!--  
  41.             连接属性 -->  
  42.     </bean>  
  43.   
  44.     <bean id="dataSourceOrder" class="com.alibaba.druid.pool.DruidDataSource"  
  45.         init-method="init" destroy-method="close">  
  46.         <property name="driverClassName" value="com.mysql.jdbc.Driver" />  
  47.         <property name="url"  
  48.             value="jdbc:mysql://IP:8066/hx_maintain?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true" />  
  49.         <property name="username" value="" />  
  50.         <property name="password" value="" />  
  51.         <property name="maxActive" value="20" /><!-- 连接池最大使用连接数 -->  
  52.         <property name="initialSize" value="1" /><!-- 初始化连接大小 -->  
  53.         <property name="maxWait" value="60000" /><!-- 获取连接最大等待时间 -->  
  54.         <property name="minIdle" value="3" /><!-- 连接池最小空闲 -->  
  55.         <property name="removeAbandoned" value="true" /><!-- 自动清除无用连接 -->  
  56.         <property name="removeAbandonedTimeout" value="1800" /><!-- 清除无用连接的等待时间 -->  
  57.         <property name="connectionProperties" value="clientEncoding=UTF-8" /><!--  
  58.             连接属性 -->  
  59.     </bean>  
  60.     <!-- <bean id="multipleDataSource" class="com.hxqc.accessory.datasource.MultipleDataSource">   
  61.         <property name="defaultTargetDataSource" ref="dataSource" /> <property name="targetDataSources">   
  62.         <map> <entry key="dataSource" value-ref="dataSource" /> <entry key="dataSourceOrder"   
  63.         value-ref="dataSourceOrder" /> </map> </property> </bean> -->  
  64.     <bean id="dataSource"  
  65.         class="com.hxqc.accessory.datasource.ThreadLocalRountingDataSource">  
  66.         <property name="defaultTargetDataSource" ref="dataSourceDefault" />  
  67.         <property name="targetDataSources">  
  68.             <map key-type="com.hxqc.accessory.datasource.DataSources">  
  69.                 <entry key="DATASOURCE_DEFAULT" value-ref="dataSourceDefault" />  
  70.                 <entry key="DATASOURCE_ORDER" value-ref="dataSourceOrder" />  
  71.                 <!-- 这里还可以加多个dataSource -->  
  72.             </map>  
  73.         </property>  
  74.     </bean>  
  75.     <!-- 多数据源配置使用结束 -->  
  76.     <!-- myBatis文件 -->  
  77.     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  78.         <property name="dataSource" ref="dataSource" />  
  79.         <property name="configLocation" value="classpath:configuration.xml" />  
  80.         <property name="mapperLocations"  
  81.             value="classpath:com/hxqc/accessory/mapper/*Mapper.xml" />  
  82.     </bean>  
  83.   
  84.     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
  85.         <property name="basePackage"  
  86.             value="com.hxqc.accessory.mapper,com.hxqc.accessory.app.mapper,com.hxqc.accessory.web.mapper" />  
  87.         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />  
  88.     </bean>  
  89.   
  90.     <!-- 配置事务管理器 -->  
  91.     <bean id="transactionManager"  
  92.         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  93.         <property name="dataSource" ref="dataSource" />  
  94.     </bean>  
  95.   
  96.     <tx:annotation-driven transaction-manager="transactionManager" />  
  97.   
  98.     <aop:aspectj-autoproxy />  
  99.   
  100.     <context:component-scan  
  101.         base-package="com.hxqc.accessory.service,com.hxqc.accessory.*.service,com.hxqc.accessory.interceptor"></context:component-scan>  
  102.   
  103.   
  104.     <context:property-placeholder location="classpath:redis.properties" />  
  105.   
  106.     <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">  
  107.         <property name="maxIdle" value="${redis.maxIdle}" />  
  108.         <property name="maxTotal" value="${redis.maxTotal}" />  
  109.         <property name="maxWaitMillis" value="${redis.maxWaitMillis}" />  
  110.         <property name="testOnBorrow" value="true"></property>  
  111.         <property name="testOnReturn" value="true"></property>  
  112.         <property name="testWhileIdle" value="${redis.testWhileIdle}"></property>  
  113.     </bean>  
  114.   
  115.     <bean id="jedisConnectionFactory"  
  116.         class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"  
  117.         p:database="${redis.default.db}" p:host-name="${redis.host}" p:port="${redis.port}"  
  118.         p:usePool="true" p:password="${redis.pass}" p:pool-config-ref="poolConfig" />  
  119.   
  120.     <bean id="shopConnectionFactory"  
  121.         class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"  
  122.         p:database="${shop.default.db}" p:host-name="${shop.host}" p:port="${shop.port}"  
  123.         p:usePool="true" p:password="${shop.pass}" p:pool-config-ref="poolConfig" />  
  124.   
  125.     <bean id="brandConnectionFactory"  
  126.         class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"  
  127.         p:database="${brand.default.db}" p:host-name="${brand.host}" p:port="${brand.port}"  
  128.         p:usePool="true" p:password="${brand.pass}" p:pool-config-ref="poolConfig" />  
  129.   
  130.   
  131.     <bean id="brandTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">  
  132.         <property name="connectionFactory" ref="brandConnectionFactory" />  
  133.     </bean>  
  134.   
  135.     <bean id="stringTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">  
  136.         <property name="connectionFactory" ref="jedisConnectionFactory" />  
  137.     </bean>  
  138.   
  139.     <bean id="shopStringTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">  
  140.         <property name="connectionFactory" ref="shopConnectionFactory" />  
  141.     </bean>  
  142.     <!-- <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">   
  143.         <property name="connectionFactory" ref="jedisConnectionFactory" /> </bean> -->  
  144.   
  145.     <bean id="connectionFactory"  
  146.         class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory">  
  147.         <constructor-arg value="IP" />  
  148.         <property name="port" value="5672" />  
  149.         <property name="username" value="hx" />  
  150.         <property name="password" value="hx" />  
  151.         <property name="channelCacheSize" value="25" />  
  152.     </bean>  
  153.     <bean id="amqpAdmin" class="org.springframework.amqp.rabbit.core.RabbitAdmin">  
  154.         <constructor-arg ref="connectionFactory" />  
  155.     </bean>  
  156.     <bean id="rabbitTemplate" class="org.springframework.amqp.rabbit.core.RabbitTemplate">  
  157.         <constructor-arg ref="connectionFactory"></constructor-arg>  
  158.     </bean>  
  159.   
  160.     <bean id="schedulerFactoryBean"  
  161.         class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
  162.         <property name="dataSource">  
  163.             <ref bean="dataSourceDefault" />  
  164.         </property>  
  165.         <property name="jobFactory">  
  166.             <bean class="com.hxqc.accessory.quartz.SpringBeanJobFactory" />  
  167.         </property>  
  168.         <property name="quartzProperties">  
  169.             <props>  
  170.                 <prop key="org.quartz.scheduler.instanceName">quartzScheduler</prop>  
  171.                 <prop key="org.quartz.scheduler.instanceId">AUTO</prop>  
  172.                 <prop key="org.quartz.threadPool.class">org.quartz.simpl.SimpleThreadPool</prop>  
  173.                 <prop key="org.quartz.threadPool.threadCount">3</prop>  
  174.                 <prop key="org.quartz.threadPool.threadPriority">5</prop>  
  175.                 <prop key="org.quartz.jobStore.misfireThreshold">60000</prop>  
  176.                 <prop key="org.quartz.jobStore.class">org.quartz.impl.jdbcjobstore.JobStoreTX</prop>  
  177.                 <prop key="org.quartz.jobStore.driverDelegateClass">org.quartz.impl.jdbcjobstore.StdJDBCDelegate </prop>  
  178.                 <prop key="org.quartz.jobStore.selectWithLockSQL">SELECT * FROM {0}LOCKS UPDLOCK WHERE LOCK_NAME = ?  
  179.                 </prop>  
  180.                 <prop key="org.quartz.jobStore.tablePrefix">QRTZ_</prop>  
  181.                 <prop key="org.quartz.jobStore.isClustered">true</prop>  
  182.                 <prop key="org.quartz.jobStore.clusterCheckinInterval">20000</prop>  
  183.             </props>  
  184.         </property>  
  185.         <property name="applicationContextSchedulerContextKey" value="applicationContextKey" />  
  186.         <property name="autoStartup" value="true" />  
  187.     </bean>  
  188.       
  189.     <task:annotation-driven/>    
  190.     <!-- 上线后开启,定时优化索引  
  191.     <bean id="systemScheduleJob" class="com.hxqc.accessory.quartz.SystemScheduleJob"></bean>  
  192.      -->  
  193. </beans>  
2、JAVA文件DataSources.class

[java]  view plain  copy
  1. package com.hxqc.accessory.datasource;  
  2.   
  3. public enum DataSources {  
  4.     DATASOURCE_DEFAULT, DATASOURCE_ORDER  
  5. }  
DataSourceAnnotation.class

[java]  view plain  copy
  1. package com.hxqc.accessory.interceptor;  
  2.   
  3. import java.lang.annotation.Documented;  
  4. import java.lang.annotation.ElementType;  
  5. import java.lang.annotation.Retention;  
  6. import java.lang.annotation.RetentionPolicy;  
  7. import java.lang.annotation.Target;  
  8.   
  9. @Target({ ElementType.PARAMETER, ElementType.METHOD })  
  10. @Retention(RetentionPolicy.RUNTIME)  
  11. @Documented  
  12. public @interface DataSourceAnnotation {  
  13.     com.hxqc.accessory.datasource.DataSources value();  
  14. }  
DataSourceInterceptor
[java]  view plain  copy
  1. package com.hxqc.accessory.interceptor;  
  2.   
  3. import java.lang.reflect.Method;  
  4.   
  5. import org.aspectj.lang.JoinPoint;  
  6. import org.aspectj.lang.ProceedingJoinPoint;  
  7. import org.aspectj.lang.Signature;  
  8. import org.aspectj.lang.annotation.Around;  
  9. import org.aspectj.lang.annotation.Aspect;  
  10. import org.aspectj.lang.reflect.MethodSignature;  
  11. import org.slf4j.Logger;  
  12. import org.springframework.core.annotation.Order;  
  13. import org.springframework.stereotype.Component;  
  14.   
  15. import com.hxqc.accessory.datasource.DataSourceTypeManager;  
  16.   
  17. @Aspect  
  18. // for aop  
  19. @Component  
  20. // for auto scan  
  21. @Order(0)  
  22. // execute before @Transactional  
  23. public class DataSourceInterceptor {  
  24.   
  25.     private static final Logger LOG = org.slf4j.LoggerFactory  
  26.             .getLogger(DataSourceInterceptor.class);  
  27.   
  28.     // @Before("execution(public * com.hxqc.accessory.service.AmbOrderService.*(..))")  
  29.     @Around("execution(public * com.hxqc.accessory.service.*.*(..)) && @annotation(com.hxqc.accessory.interceptor.DataSourceAnnotation)")  
  30.     // @Around("execution(public * *Order*(..))")  
  31.     public Object beforeOrder(ProceedingJoinPoint pjp) throws Throwable {  
  32.         DataSourceAnnotation dataSourceAnnotation = getAnnotation(pjp);  
  33.         LOG.info("切换后数据源:{}", dataSourceAnnotation.value());  
  34.         DataSourceTypeManager.set(dataSourceAnnotation.value());  
  35.         try {  
  36.             Object value = pjp.proceed();  
  37.             return value;  
  38.         } finally {  
  39.             DataSourceTypeManager.reset();  
  40.         }  
  41.     }  
  42.   
  43.     /** 
  44.      * 获得注释内容 
  45.      *  
  46.      * @param joinPoint 
  47.      * @return 
  48.      */  
  49.     private DataSourceAnnotation getAnnotation(JoinPoint joinPoint) {  
  50.         Signature signature = joinPoint.getSignature();  
  51.         MethodSignature methodSignature = (MethodSignature) signature;  
  52.         Method method = methodSignature.getMethod();  
  53.         if (method != null) {  
  54.             return method.getAnnotation(DataSourceAnnotation.class);  
  55.         }  
  56.         return null;  
  57.     }  
  58.   
  59. }  
DataSourceTypeManager.class
[java]  view plain  copy
  1. package com.hxqc.accessory.datasource;  
  2.   
  3. public class DataSourceTypeManager {  
  4.     private static final ThreadLocal<DataSources> dataSourceTypes = new ThreadLocal<DataSources>() {  
  5.         @Override  
  6.         protected DataSources initialValue() {  
  7.             return DataSources.DATASOURCE_DEFAULT;  
  8.         }  
  9.     };  
  10.   
  11.     public static DataSources get() {  
  12.         return dataSourceTypes.get();  
  13.     }  
  14.   
  15.     public static void set(DataSources dataSourceType) {  
  16.         dataSourceTypes.set(dataSourceType);  
  17.     }  
  18.   
  19.     public static void reset() {  
  20.         dataSourceTypes.set(DataSources.DATASOURCE_DEFAULT);  
  21.     }  
  22. }  

ThreadLocalRountingDataSource.class

[java]  view plain  copy
  1. package com.hxqc.accessory.datasource;  
  2.   
  3. import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;  
  4.   
  5. public class ThreadLocalRountingDataSource extends AbstractRoutingDataSource {  
  6.     @Override  
  7.     protected Object determineCurrentLookupKey() {  
  8.         return DataSourceTypeManager.get();  
  9.     }  
  10. }  

切换数据源:DataSourceTypeManager.set(DataSources.DATASOURCE_ORDER);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值