整体大概流程:java
一、配置数据源、帐密(帐密一致,文章很少阐述)mysql
driverClassName = com.mysql.jdbc.Driver
validationQuery = SELECT 1 FROM DUALspring
# 腕表 jdbc_url = jdbc:mysql://127.0.0.1:3306/do_wave_new?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true # 车机 jdbc_url2 = jdbc:mysql://127.0.0.1:3306/car_internet?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true jdbc_username = root
jdbc_password = dowave!@#888
jdbc_initialSize = 2 jdbc_minIdle = 1 jdbc_maxActive = 500 jdbc_maxWait = 1800000
二、Mybytis.xml 配置数据源sql
<!-- 配置数据源 --> <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${driverClassName}" /> <property name="url" value="${jdbc_url}" /> <property name="username" value="${jdbc_username}" /> <property name="password" value="${jdbc_password}" /> <!-- 初始化链接大小 --> <property name="initialSize" value="${jdbc_initialSize}" /> <!-- 链接池最大使用链接数量 --> <property name="maxActive" value="${jdbc_maxActive}" /> <!-- 链接池最小空闲 --> <property name="minIdle" value="${jdbc_minIdle}" /> <!-- 获取链接最大等待时间 毫秒--> <property name="maxWait" value="${jdbc_maxWait}" /> <!-- 打开PSCache,而且指定每一个链接上PSCache的大小 --> <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> <property name="validationQuery" value="${validationQuery}" /> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <!-- 配置间隔多久才进行一次检测,检测须要关闭的空闲链接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个链接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="300000" /> <!-- 超过期间限制是否回收: 打开removeAbandoned功能 --> <property name="removeAbandoned" value="true" /> <!-- 超时时间:1800秒,也就是30分钟 --> <property name="removeAbandonedTimeout" value="1800" /> <!-- 关闭abanded链接时输出错误日志 --> <property name="logAbandoned" value="true" /> <!-- 监控数据库 --> <!-- <property name="filters" value="mergeStat" /> --> <property name="filters" value="stat" /> <!-- 非公平锁 --> <property name="useUnfairLock" value="true" /> </bean> <!-- 配置数据源 --> <bean name="dataSource2" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${driverClassName}" /> <property name="url" value="${jdbc_url2}" /> <property name="username" value="${jdbc_username}" /> <property name="password" value="${jdbc_password}" /> <!-- 初始化链接大小 --> <property name="initialSize" value="${jdbc_initialSize}" /> <!-- 链接池最大使用链接数量 --> <property name="maxActive" value="${jdbc_maxActive}" /> <!-- 链接池最小空闲 --> <property name="minIdle" value="${jdbc_minIdle}" /> <!-- 获取链接最大等待时间 毫秒--> <property name="maxWait" value="${jdbc_maxWait}" /> <!-- 打开PSCache,而且指定每一个链接上PSCache的大小 --> <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> <property name="validationQuery" value="${validationQuery}" /> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <!-- 配置间隔多久才进行一次检测,检测须要关闭的空闲链接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个链接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="300000" /> <!-- 超过期间限制是否回收: 打开removeAbandoned功能 --> <property name="removeAbandoned" value="true" /> <!-- 超时时间:1800秒,也就是30分钟 --> <property name="removeAbandonedTimeout" value="1800" /> <!-- 关闭abanded链接时输出错误日志 --> <property name="logAbandoned" value="true" /> <!-- 监控数据库 --> <!-- <property name="filters" value="mergeStat" /> --> <property name="filters" value="stat" /> <!-- 非公平锁 --> <property name="useUnfairLock" value="true" /> </bean> <bean id="dynamicDataSource" class="com.dowave.datasource.DynamicDataSource"> <property name="targetDataSources"> <map key-type="java.lang.String"> <!-- 主库-腕表 --> <entry key="ds1" value-ref="dataSource"/> <!-- 副库-车机 --> <entry key="ds2" value-ref="dataSource2"/> </map> </property> <!--默认数据源--> <property name="defaultTargetDataSource" ref="dataSource"/> </bean> <!-- myBatis文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dynamicDataSource" /> <!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 --> <property name="mapperLocations" value="classpath:com/XXXXXX/entity/mapper/*.xml" /> </bean>
三、数据源切换工具类数据库
枚举类:表明对应的数据源express
public enum DataSourceEnum { DS1("ds1"), DS2("ds2"); private String key; DataSourceEnum(String key) { this.key = key; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } }
建立建立 DynamicDataHolder 用于持有当前线程中使用的数据源标识mybatis
public class DataSourceHolder { private static final ThreadLocal<String> dataSources = new ThreadLocal<String>(); public static void setDataSources(String dataSource) { dataSources.set(dataSource); } public static String getDataSources() { return dataSources.get(); } }
建立DynamicDataSource的类,继承AbstractRoutingDataSource并重写determineCurrentLookupKey方法app
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DataSourceHolder.getDataSources(); } }
四、自动切换数据源,利用AOP,进行自动切换数据源
建立切面类 DataSourceExchange,切面的规则能够自定义,根据本身的项目作本身的规则,我这边用 citn 表示不一样的数据源。ide
public class DataSourceExchange { public void before(JoinPoint point) { // 获取目标对象的类类型 Class<?> aClass = point.getTarget().getClass(); String c = aClass.getName(); String[] s = c.split("\\."); // 获取包名用于区分不一样数据源 String packageName = s[3]; if ("citn".equals(packageName)) { DataSourceHolder.setDataSources(DataSourceEnum.DS2.getKey()); System.out.println("数据源:" + DataSourceEnum.DS2.getKey()); } else { DataSourceHolder.setDataSources(DataSourceEnum.DS1.getKey()); System.out.println("数据源:" + DataSourceEnum.DS1.getKey()); } } /** * 执行后将数据源置为默认 */ public void after() { DataSourceHolder.setDataSources(DataSourceEnum.DS1.getKey()); } }
五、Spring.xml 配置AOP切面,expression 为切入点,根据本身项目调整。工具
<bean id="dataSourceExchange" class="com.dowave.datasource.DataSourceExchange" />
<aop:config>
<aop:aspect ref="dataSourceExchange">
<aop:pointcut id="dataSourcePointcut" expression="execution(* com.XXXXXX.**.service.impl.*ServiceImpl.*(..))" />
<aop:before pointcut-ref="dataSourcePointcut" method="before" />
<aop:after pointcut-ref="dataSourcePointcut" method="after" />
</aop:aspect>
</aop:config>
六、须要使用其余数据源在 *ServiceImpl 的位置切换数据源便可
@Service public class AdminServiceImpl implements IAdminService { @Autowired private AdminDao adminDao; @Autowired private AgentDao agentDao; @Autowired private AdminAgentDao adminAgentDao; @Override public Admin login(AdminForm form) { DataSourceHolder.setDataSources(DataSourceEnum.DS2.getKey()); return adminDao.login(form); }
}
附:结构目录