spring mybatis 配置多数据源

2017-01-10 10:03:40来源:oschina作者:longjunping人点击

package com.*.blive.common;
/**
* Created by longjunping on 2017/1/8.
* 1、保存一个线程安全的DatabaseType容器
*/
public class DatabaseContextHolder {
private static final ThreadLocal contextHolder = new ThreadLocal<>();
public static void setDatabaseType(DatabaseType type){
contextHolder.set(type);
}
public static DatabaseType getDatabaseType(){
return contextHolder.get();
}
} package com.*.blive.common;
/**
* Created by longjunping on 2017/1/8.
* 列出所有的数据源key(常用数据库名称来命名)
* 注意:
* 1)这里数据源与数据库是一对一的
* 2)DatabaseType中的变量名称就是数据库的名称
*/
public enum DatabaseType {
iblivedb,bizexchangedb
}
package com.*.blive.common;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* Created by longjunping on 2017/1/8.
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
/**
* 动态数据源(需要继承AbstractRoutingDataSource)
*/
protected Object determineCurrentLookupKey() {
return DatabaseContextHolder.getDatabaseType();
}
} package com.*.blive.configuration;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.lecloud.blive.common.DatabaseType;
import com.lecloud.blive.common.DynamicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* Created by longjunping on 2017/1/8.
*/
@Configuration
@MapperScan(basePackages = "com.*.blive.mapper")
public class MyBatisConfig {
@Value("${statistics.datasource.url}")
private String url;
@Value("${statistics.datasource.username}")
private String username;
@Value("${statistics.datasource.password}")
private String password;
@Value("${statistics.datasource.driver-class-name}")
private String driverName;
@Value("${os.datasource.url}")
private String osurl;
@Value("${os.datasource.username}")
private String osusername;
@Value("${os.datasource.password}")
private String ospassword;
@Value("${os.datasource.driver-class-name}")
private String osdriverName;
// 配置初始化大小、最小、最大
@Value("${druid.initialSize:1}")
private int initialSize;
@Value("${druid.minIdle:1}")
private int minIdle;
@Value("${druid.maxActive:100}")
private int maxActive;
// 配置获取连接等待超时的时间
@Value("${druid.maxWait:20000}")
private Integer maxWait;
// 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
@Value("${druid.timeBetweenEvictionRunsMillis:60000}")
private Integer timeBetweenEvictionRunsMillis;
@Value("${druid.validationQuery:select 'x'}")
private String validationQuery;
@Value("${druid.testWhileIdle:true}")
private boolean testWhileIdle;
@Value("${druid.testOnBorrow:false}")
private boolean testOnBorrow;
@Value("${druid.testOnReturn:false}")
private boolean testOnReturn;
@Value("${druid.removeAbandoned:true}")
private boolean removeAbandoned;
@Value("${druid.removeAbandonedTimeout:180}")
private int removeAbandonedTimeout;
@Value("${druid.logAbandoned:true}")
private boolean logAbandoned;
@Value("${app.debug:false}")
private boolean debug;@Autowired
private Environment env;
/**
* 创建数据源(数据源的名称:方法名可以取为XXXDataSource(),XXX为数据库名称,该名称也就是数据源的名称)
*/
@Bean
public DataSource ibliveDbDataSource() throws Exception {
DataSource dataSource = new DataSource();
dataSource.setUrl(osurl);
dataSource.setUsername(osusername);
dataSource.setPassword(ospassword);
dataSource.setDriverClassName(osdriverName);
dataSource.setInitialSize(initialSize);
dataSource.setMinIdle(minIdle);
dataSource.setMaxActive(maxActive);
dataSource.setMaxWait(maxWait);
dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
dataSource.setValidationQuery(validationQuery);
dataSource.setTestWhileIdle(testWhileIdle);
dataSource.setTestOnBorrow(testOnBorrow);
dataSource.setTestOnReturn(testOnReturn);
// 调试查看程序线程泄露的地方
if (debug) {
dataSource.setRemoveAbandoned(removeAbandoned);
dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout);
dataSource.setLogAbandoned(logAbandoned);
}
return dataSource;
}
@Bean
public DataSource bizexchangedbDateSource() {
DataSource dataSource = new DataSource();
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setDriverClassName(driverName);
dataSource.setInitialSize(initialSize);
dataSource.setMinIdle(minIdle);
dataSource.setMaxActive(maxActive);
dataSource.setMaxWait(maxWait);
dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
dataSource.setValidationQuery(validationQuery);
dataSource.setTestWhileIdle(testWhileIdle);
dataSource.setTestOnBorrow(testOnBorrow);
dataSource.setTestOnReturn(testOnReturn);
// 调试查看程序线程泄露的地方
if (debug) {
dataSource.setRemoveAbandoned(removeAbandoned);
dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout);
dataSource.setLogAbandoned(logAbandoned);
}
return dataSource;
}
/**
* @Primary 该注解表示在同一个接口有多个实现类可以注入的时候,默认选择哪一个,而不是让@autowire注解报错
* @Qualifier 根据名称进行注入,通常是在具有相同的多个类型的实例的一个注入(例如有多个DataSource类型的实例)
*/
@Bean
@Primary
public DynamicDataSource dataSource(@Qualifier("ibliveDbDataSource") DataSource ibliveDbDataSource,
@Qualifier("bizexchangedbDateSource") DataSource bizexchangedbDateSource) {
Map targetDataSources = new HashMap<>();
targetDataSources.put(DatabaseType.iblivedb, ibliveDbDataSource);
targetDataSources.put(DatabaseType.bizexchangedb, bizexchangedbDateSource);
DynamicDataSource dataSource = new DynamicDataSource();
dataSource.setTargetDataSources(targetDataSources);// 该方法是AbstractRoutingDataSource的方法
dataSource.setDefaultTargetDataSource(ibliveDbDataSource);// 默认的datasource设置为ibliveDbDataSource
return dataSource;
}
/**
* 根据数据源创建SqlSessionFactory
*/
@Bean
public SqlSessionFactory sqlSessionFactory(DynamicDataSource ds) throws Exception {
SqlSessionFactoryBean fb = new SqlSessionFactoryBean();
fb.setDataSource(ds);// 指定数据源(这个必须有,否则报错)
fb.setConfigLocation(new ClassPathResource("/mybatis-config.xml"));
return fb.getObject();
}
/**
* 配置事务管理器
*/
@Bean
public DataSourceTransactionManager transactionManager(DynamicDataSource dataSource) throws Exception {
return new DataSourceTransactionManager(dataSource);
}
} public interface InteractionMapper {
List getActiveProgramId(String statisticsTime);
List getInteractionInfoByPrograms(String programId);
int getOptionCountById(Long optionId);
} @Service("collectInteractionService")
public class CollectInteractionServiceImpl {
@Autowired
InteractionMapper interactionMapper;
public List getActiveProgramId(String statisticsTime){
DatabaseContextHolder.setDatabaseType(DatabaseType.iblivedb);
return interactionMapper.getActiveProgramId(statisticsTime);
}
public List getInteractionInfoByPrograms(String programId){
DatabaseContextHolder.setDatabaseType(DatabaseType.iblivedb);
return interactionMapper.getInteractionInfoByPrograms(programId);
}
public int getOptionCountById(Long optionId){
return interactionMapper.getOptionCountById(optionId);
}
}

mybatis-config.xml 配置文件


<?xml version="1.0" encoding="UTF-8" ?>
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">


















application.properties 配置文件


os.datasource.url=jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
os.datasource.username=root
os.datasource.password=root
os.datasource.driver-class-name=com.mysql.jdbc.Driver
statistics.datasource.url=jdbc:mysql://localhost:3306/db2?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&allowMultiQueries=true&zeroDateTimeBehavior=convertToNull
statistics.datasource.username=root
statistics.datasource.password=root
statistics.datasource.driver-class-name=com.mysql.jdbc.Driver

参考:http://www.cnblogs.com/java-zhao/p/5413845.html

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台