java 实现运行时连接多data source数据源
2016-05-11 本文已影响512人
stepyu
-
DynamicDataSource
继承org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource
,实现抽象方法protected Object determineCurrentLookupKey()
protected Object determineCurrentLookupKey() { return DatabaseContextHolder.getDatabaseType(); }
DatabaseContextHolder
中定义一个静态的ThreadLocal<DatabaseType>
的contextHolder
public class DatabaseContextHolder { private static final ThreadLocal<DatabaseType> contextHolder = new ThreadLocal<DatabaseType>(); public static void setDatabaseType(DatabaseType databaseType) { contextHolder.set(databaseType); } public static DatabaseType getDatabaseType() { return (DatabaseType) contextHolder.get(); } public static void clearDatabaseType() { contextHolder.remove(); }
}
```
`DatabaseType` 是一个枚举,枚举了项目要连接的所有的数据库,
创建各个数据库的`DataSource`
```java
com.alibaba.druid.pool.DruidDataSource dataSource = new com.alibaba.druid.pool.DruidDataSource()
dataSource.setDriverClassName(env.getProperty("xxx.driverClassName"));
dataSource.setUrl(env.getProperty("xxx.url"));
dataSource.setUsername(env.getProperty("xxx.username"));
dataSource.setPassword(env.getProperty("xxx.password"));
dataSource.setInitialSize(Integer.parseInt(env.getProperty("datasource.initialSize")));
dataSource.setMinIdle(Integer.parseInt(env.getProperty("datasource.minIdle")));
dataSource.setMaxActive(Integer.parseInt(env.getProperty("datasource.maxActive")));
dataSource.setMaxWait(Long.parseLong(env.getProperty("datasource.maxWait")));
dataSource.setRemoveAbandoned(Boolean.parseBoolean(env.getProperty("datasource.removeAbandoned")));
dataSource.setRemoveAbandonedTimeout(Integer.parseInt(env.getProperty("datasource.removeAbandonedTimeout")));
dataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(env.getProperty("datasource.timeBetweenEvictionRunsMillis")));
dataSource.setMinEvictableIdleTimeMillis(Long.parseLong(env.getProperty("datasource.minEvictableIdleTimeMillis")));
dataSource.setPoolPreparedStatements(Boolean.parseBoolean(env.getProperty("datasource.poolPreparedStatements")));
dataSource.setMaxPoolPreparedStatementPerConnectionSize(Integer.parseInt(env.getProperty("datasource.maxPoolPreparedStatementPerConnectionSize")));
dataSource.setValidationQuery(env.getProperty("datasource.validationQuery"));
```
`datasource` 设置`targetDataSources`
```java
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DatabaseType.xxx, mailServerDataSource());
datasource.setTargetDataSources(Map<Object,Object>)
```