1.建立一個類,使用註解的形式,方便使用,該註解使用在Service層java
@Target({ElementType.TYPE,ElementType.METHOD})mysql
@Retention(RetentionPolicy.RUNTIME)spring
public @interface DataSource {
String value();
}sql
2.建立一個切面方法,用於攔截全部的Service方法的調用,分配數據源數據庫
public class DataSourceAspect {express
/**
* 攔截目標方法,獲取由@DataSource指定的數據源標識,設置到線程存儲中以便切換數據源
*
* @param point
* @throws Exception
*/
public void intercept(JoinPoint point) throws Exception {
Class<?> target = point.getTarget().getClass();
MethodSignature signature = (MethodSignature) point.getSignature();
// 默認使用目標類型的註解,若是沒有則使用其實現接口的註解
for (Class<?> clazz : target.getInterfaces()) {
resolveDataSource(clazz, signature.getMethod());
}
resolveDataSource(target, signature.getMethod());
}
/**
* 提取目標對象方法註解和類型註解中的數據源標識
*
* @param clazz
* @param method
*/
private void resolveDataSource(Class<?> clazz, Method method) {
try {
Class<?>[] types = method.getParameterTypes();
// 默認使用類型註解
if (clazz.isAnnotationPresent(DataSource.class)) {
DataSource source = clazz.getAnnotation(DataSource.class);
DynamicDataSourceHolder.setDataSource(source.value());
}
// 方法註解能夠覆蓋類型註解
Method m = clazz.getMethod(method.getName(), types);
if (m != null && m.isAnnotationPresent(DataSource.class)) {
DataSource source = m.getAnnotation(DataSource.class);
DynamicDataSourceHolder.setDataSource(source.value());
}
} catch (Exception e) {
System.out.println(clazz + ":" + e.getMessage());
}
}
}session
3.mybatis
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
// 從自定義的位置獲取數據源標識
return DynamicDataSourceHolder.getDataSource();
}
}多線程
4.併發
public class DynamicDataSourceHolder {
/**
* 注意:數據源標識保存在線程變量中,避免多線程操做數據源時互相干擾
*/
private static final ThreadLocal<String> THREAD_DATA_SOURCE = new ThreadLocal<String>();
/**
* 配置mysql數據源
*/
public static final String mysql="mysql";
/**
* 配置oracle數據源
*/
public static final String oracle="oracle";
/**
* 配置sqlServer數據源
*/
public static final String sqlServer="sqlServer";
public static String getDataSource() {
return THREAD_DATA_SOURCE.get();
}
public static void setDataSource(String dataSource) {
THREAD_DATA_SOURCE.set(dataSource);
}
public static void clearDataSource() {
THREAD_DATA_SOURCE.remove();
}
}
5.配置配置文件
dbconfig.properties 把數據源信息儲存到配置文件中,也能夠配在spring-application中
url:jdbc:mysql://localhost:3306/parkmanager?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
driverClassName:com.mysql.jdbc.Driver
username:root
password:ok
filters:stat
maxActive:20
initialSize:1
maxWait:60000
minIdle:10
maxIdle:15
timeBetweenEvictionRunsMillis:60000
minEvictableIdleTimeMillis:300000
validationQuery:SELECT 'x'
testWhileIdle:true
testOnBorrow:false
testOnReturn:false
maxOpenPreparedStatements:20
removeAbandoned:true
removeAbandonedTimeout:1800
logAbandoned:true
ApplicationContext-dataSource.xml 一個對數據源操做的配置文件
<!-- 阿里 druid數據庫鏈接池 -->
<bean id="mysqlDataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<!-- 數據庫基本信息配置 -->
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<property name="driverClassName" value="${driverClassName}" />
<property name="filters" value="${filters}" />
<!-- 最大併發鏈接數 -->
<property name="maxActive" value="${maxActive}" />
<!-- 初始化鏈接數量 -->
<property name="initialSize" value="${initialSize}" />
<!-- 配置獲取鏈接等待超時的時間 -->
<property name="maxWait" value="${maxWait}" />
<!-- 最小空閒鏈接數 -->
<property name="minIdle" value="${minIdle}" />
<!-- 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" />
<!-- 配置一個鏈接在池中最小生存的時間,單位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />
<property name="validationQuery" value="${validationQuery}" />
<property name="testWhileIdle" value="${testWhileIdle}" />
<property name="testOnBorrow" value="${testOnBorrow}" />
<property name="testOnReturn" value="${testOnReturn}" />
<property name="maxOpenPreparedStatements" value="${maxOpenPreparedStatements}" />
<!-- 打開removeAbandoned功能 -->
<property name="removeAbandoned" value="${removeAbandoned}" />
<!-- 1800秒,也就是30分鐘 -->
<property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" />
<!-- 關閉abanded鏈接時輸出錯誤日誌 -->
<property name="logAbandoned" value="${logAbandoned}" />
</bean>
多個數據源 把上面的配置複製粘貼就好
把全部數據源放在一個容器中方便sqlsession管理
<bean id="dataSource" class="com.flc.util.dataSource.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<!-- 指定lookupKey和與之對應的數據源 -->
<entry key="mysql" value-ref="mysqlDataSource"></entry>
<entry key="oracle" value-ref="oracleDataSource"></entry>
<entry key="sqlServer" value-ref="sqlServerDataSource"></entry>
</map>
</property>
<!-- 這裏能夠指定默認的數據源 -->
<property name="defaultTargetDataSource" ref="mysqlDataSource" />
</bean>
配置sqlsession管理
<!-- sql會話模版 -->
<!--這裏使用的是sqlSessionTemplate,也能夠不實用,具體狀況分析-->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg ref="sqlSessionFactory" />
</bean>
<!-- 配置mybatis -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property>
<!-- mapper掃描 -->
<property name="mapperLocations" value="classpath:mybatis/*/*.xml"></property>
</bean>
配置事務管理器
<!-- 攔截全部service層 同一走自定義的dataSourceAspect -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:advice id="Myadvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="delete*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception"/>
<tx:method name="insert*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<tx:method name="update*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<tx:method name="save*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<!-- <tx:method name="find*" propagation="SUPPORTS" read-only="true"/> -->
</tx:attributes>
</tx:advice>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<bean id="dataSourceAspect" class="com.flc.util.dataSource.DataSourceAspect" ></bean>
<aop:config>
<aop:aspect ref="dataSourceAspect" >
<!-- 攔截全部service方法 -->
<!-- 再service層打註解 -->
<aop:pointcut id="dataSourcePointcut" expression="execution(* com.flc.service..*(..))"/>
<aop:before pointcut-ref="dataSourcePointcut" method="intercept" />
</aop:aspect>
</aop:config>
使用方法
@Service("userService") //service調用
@DataSource(value=DynamicDataSourceHolder.mysql) //選擇mysql數據庫
public class UserService implements UserManager{
}