Druid动态数据源配置

时间:2022-12-03 20:50:56

上文已经讲了单个数据源的Druid的配置(http://www.cnblogs.com/nbfujx/p/7686634.html

Druid动态数据源配置 主要是继承AbstractRoutingDataSource再通过AOP来实现动态数据源切换

Druid动态数据源的使用(基于原先的程序调整

使用步骤:

1.调整配置属性文件:mybatis.properties (增加DataSource连接参数)

 master.driver=com.mysql.jdbc.Driver
master.url=jdbc:mysql://127.0.0.1:3306/jawavesys
master.username=root
master.password=jawave88
#定义初始连接数
master.initialSize=0
#定义最大连接数
master.maxActive=20
#定义最大空闲
master.maxIdle=20
#定义最小空闲
master.minIdle=1
#定义最长等待时间
master.maxWait=60000 slave.driver=com.mysql.jdbc.Driver
slave.url=jdbc:mysql://127.0.0.1:3306/jawave_eform
slave.username=root
slave.password=jawave88
#定义初始连接数
slave.initialSize=0
#定义最大连接数
slave.maxActive=20
#定义最大空闲
slave.maxIdle=20
#定义最小空闲
slave.minIdle=1
#定义最长等待时间
slave.maxWait=60000

2.调整SPRING配置文件:spring-base.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
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.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <context:component-scan base-package="com.goku.druid.demo">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan> <!-- 引入配置文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:mybatis.properties" />
</bean> <bean id="masterDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="driverClassName" value="${master.driver}" />
<property name="url" value="${master.url}" />
<property name="username" value="${master.username}" />
<property name="password" value="${master.password}" />
<!-- 初始化连接大小 -->
<property name="initialSize" value="${master.initialSize}"></property>
<!-- 连接池最大数量 -->
<property name="maxActive" value="${master.maxActive}"></property>
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="${master.maxIdle}"></property>
<!-- 连接池最小空闲 -->
<property name="minIdle" value="${master.minIdle}"></property>
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="${master.maxWait}"></property>
<!-- 这里配置提交方式,默认就是TRUE,可以不用配置 -->
<property name="defaultAutoCommit" value="true" />
<!-- 验证连接有效与否的SQL,不同的数据配置不同 -->
<property name="validationQuery" value="select 1 " />
<!--通过别名的方式配置扩展插件,监控统计用的filter:stat 日志用的filter:log4j 防御sql注入的filter:wall-->
<property name="filters" value="stat,log4j" />
<property name="proxyFilters">
<list>
<ref bean="stat-filter" />
<ref bean="log-filter"/>
</list>
</property>
</bean> <bean id="slaveDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="driverClassName" value="${slave.driver}" />
<property name="url" value="${slave.url}" />
<property name="username" value="${slave.username}" />
<property name="password" value="${slave.password}" />
<!-- 初始化连接大小 -->
<property name="initialSize" value="${slave.initialSize}"></property>
<!-- 连接池最大数量 -->
<property name="maxActive" value="${slave.maxActive}"></property>
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="${slave.maxIdle}"></property>
<!-- 连接池最小空闲 -->
<property name="minIdle" value="${slave.minIdle}"></property>
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="${slave.maxWait}"></property>
<!-- 这里配置提交方式,默认就是TRUE,可以不用配置 -->
<property name="defaultAutoCommit" value="true" />
<!-- 验证连接有效与否的SQL,不同的数据配置不同 -->
<property name="validationQuery" value="select 1 " />
<!--通过别名的方式配置扩展插件,监控统计用的filter:stat 日志用的filter:log4j 防御sql注入的filter:wall-->
<property name="filters" value="stat,log4j" />
<property name="proxyFilters">
<list>
<ref bean="stat-filter" />
<ref bean="log-filter"/>
</list>
</property>
</bean> <bean id="dataSource" class="com.goku.druid.demo.util.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<!-- master -->
<entry key="master" value-ref="masterDataSource"/>
<!-- slave -->
<entry key="slave" value-ref="slaveDataSource"/>
</map>
</property>
<property name="defaultTargetDataSource" ref="masterDataSource"/>
</bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:mapping/**/*.xml"></property>
</bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.goku.druid.demo.mapper" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean> <!-- 开启事务注解驱动 -->
<tx:annotation-driven transaction-manager="transactionManager"/> <!-- 为业务逻辑层的方法解析@DataSource注解 为当前线程的routeholder注入数据源key -->
<bean id="dataSourceAspect" class="com.goku.druid.demo.util.DataSourceAspect" />
<aop:config proxy-target-class="true">
<aop:aspect id="dataSourceAspect" ref="dataSourceAspect" order="1">
<aop:pointcut id="tx" expression="execution(* com.goku.druid.demo.service..*.*(..)) "/>
<aop:before pointcut-ref="tx" method="before" />
</aop:aspect>
</aop:config> <!--监控统计-->
<bean id="stat-filter" class="com.alibaba.druid.filter.stat.StatFilter">
<property name="slowSqlMillis" value="10000" />
<property name="logSlowSql" value="true" />
</bean> <!--日志-->
<bean id="log-filter" class="com.alibaba.druid.filter.logging.Log4jFilter">
<property name="statementExecutableSqlLogEnable" value="true" />
</bean> </beans>

3.接下写AbstractRoutingDataSource继承类

package com.goku.druid.demo.util;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
* Created by nbfujx on 2017/10/18.
*/
public class DynamicDataSource extends AbstractRoutingDataSource { @Override
protected Object determineCurrentLookupKey() {
return DataSourceHolder.getDataSource();
} }

4.接下来写切面实现类

package com.goku.druid.demo.util;

import java.lang.reflect.Method;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature; /**
* Created by nbfujx on 2017/10/18.
*/
public class DataSourceAspect { /**
* 在dao层方法之前获取datasource对象之前在切面中获取数据源
*/
public void before(JoinPoint point)
{
Object target = point.getTarget();
System.out.println(target.toString());
String method = point.getSignature().getName();
System.out.println(method);
Class<?>[] classz = target.getClass().getInterfaces();
Class<?>[] parameterTypes = ((MethodSignature) point.getSignature())
.getMethod().getParameterTypes();
try {
Method m = classz[0].getMethod(method, parameterTypes);
System.out.println("method"+ m.getName());
if (m != null && m.isAnnotationPresent(DataSource.class)) {
DataSource data = m.getAnnotation(DataSource.class);
System.out.println("dataSource:"+data.value());
DataSourceHolder.putDataSource(data.value());
} } catch (Exception e) {
e.printStackTrace();
}
}
}

5.还有拿到数据元的类

package com.goku.druid.demo.util;

/**
* Created by nbfujx on 2017/10/18.
*/
public class DataSourceHolder {
public static final ThreadLocal<String> holder = new ThreadLocal<String>(); /**
* 设置数据源
*/
public static void putDataSource(String datasource) {
holder.set(datasource);
} /**
* 获取数据源
*/
public static String getDataSource() {
return holder.get();
} /**
* 清除数据源
*/
public static void clearDataSource() {
holder.remove();
}
}

6.DataSource数据源注解类

package com.goku.druid.demo.util;

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy; /**
* Created by nbfujx on 2017/10/18.
*/ @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DataSource {
String value();
}

7.在service层进行数据源注解切换

package com.goku.druid.demo.service;

import com.goku.druid.demo.model.FormElement;
import com.goku.druid.demo.model.UserWithBLOBs;
import com.goku.druid.demo.util.DataSource; /**
* Created by nbfujx on 2017-10-18.
*/
public interface UserService {
@DataSource("master")
UserWithBLOBs selectByPrimaryKey(String id); @DataSource("slave")
FormElement selectByPrimaryKey2(Integer id);
}

GITHUB

github :  https://github.com/nbfujx/learn-java-demo/tree/master/Goku.Dynamic.DruidDemo