package com.test.springboot.config.datasource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.boot.bind.RelaxedDataBinder;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;
import com.alibaba.druid.pool.DruidDataSource;
/**
* 动态数据源注册
* @author xiyan
*/
public class DynamicDataSourceRegister implements ImportBeanDefinitionRegistrar, EnvironmentAware {
private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceRegister.class);
// 数据源配置信息
private PropertyValues dataSourcePropertyValues;
// 默认数据源
private DataSource defaultDataSource;
// 动态数据源
private Map<String, DataSource> dynamicDataSources = new HashMap<>();
/**
* 加载多数据源配置
* Environment 是用来读取application.properties中的内容
*/
@Override
public void setEnvironment(Environment env) {
//读取application.properties中以jdbc.开头的属性
RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(env, "jdbc.");
String dsPrefixs = propertyResolver.getProperty("datasources");
for (String dsPrefix : dsPrefixs.split(",")) {// 多个数据源
Map<String, Object> map = propertyResolver.getSubProperties(dsPrefix + ".");
DataSource ds = initDataSource(map);
// 设置默认数据源
if ("ds".equals(dsPrefix)) {
defaultDataSource = ds;
} else {
dynamicDataSources.put(dsPrefix, ds);
}
dataBinder(ds, env);
}
}
/**
* 初始化数据源
* @param map
* @return
*/
public DataSource initDataSource(Map<String, Object> map) {
String driverClassName = map.get("driverClassName").toString();
String url = map.get("url").toString();
String username = map.get("username").toString();
String password = map.get("password").toString();
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
//配置最大连接
dataSource.setMaxActive(300);
//配置初始连接
dataSource.setInitialSize(20);
//配置最小连接
dataSource.setMinIdle(10);
//连接等待超时时间
dataSource.setMaxWait(60000);
//间隔多久进行检测,关闭空闲连接
dataSource.setTimeBetweenEvictionRunsMillis(60000);
//一个连接最小生存时间
dataSource.setMinEvictableIdleTimeMillis(300000);
//连接等待超时时间 单位为毫秒 缺省启用公平锁,
//并发效率会有所下降, 如果需要可以通过配置useUnfairLock属性为true使用非公平锁
dataSource.setUseUnfairLock(true);
//用来检测是否有效的sql
dataSource.setValidationQuery("select 'x'");
dataSource.setTestWhileIdle(true);
//申请连接时执行validationQuery检测连接是否有效,配置为true会降低性能
dataSource.setTestOnBorrow(false);
//归还连接时执行validationQuery检测连接是否有效,配置为true会降低性能
dataSource.setTestOnReturn(false);
//打开PSCache,并指定每个连接的PSCache大小启用poolPreparedStatements后,
//PreparedStatements 和CallableStatements 都会被缓存起来复用,
//即相同逻辑的SQL可以复用一个游标,这样可以减少创建游标的数量。
dataSource.setPoolPreparedStatements(true);
dataSource.setMaxOpenPreparedStatements(20);
try {
//配置sql监控的filter
dataSource.setFilters("stat,wall,log4j");
dataSource.init();
} catch (SQLException e) {
throw new RuntimeException("druid datasource init fail");
}
/*String dsType = map.get("dsType").toString();
Class<DataSource> dataSourceType;
DataSource dataSource = null;
try {
dataSourceType = (Class<DataSource>) Class.forName(dsType);
dataSource = DataSourceBuilder.create().driverClassName(driverClassName).url(url)
.username(username).password(password).type(dataSourceType).build();;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}*/
return dataSource;
}
/**
* 加载数据源配置信息
* @param dataSource
* @param env
*/
private void dataBinder(DataSource dataSource, Environment env) {
RelaxedDataBinder dataBinder = new RelaxedDataBinder(dataSource);
dataBinder.setIgnoreNestedProperties(false);// false
dataBinder.setIgnoreInvalidFields(false);// false
dataBinder.setIgnoreUnknownFields(true);// true
if (dataSourcePropertyValues == null) {
Map<String, Object> values = new RelaxedPropertyResolver(env, "datasource").getSubProperties(".");
dataSourcePropertyValues = new MutablePropertyValues(values);
}
dataBinder.bind(dataSourcePropertyValues);
}
/**
* 注册数据源been
*/
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
// 将主数据源添加到更多数据源中
targetDataSources.put("dataSource", defaultDataSource);
// 添加更多数据源
targetDataSources.putAll(dynamicDataSources);
// 创建DynamicDataSource
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(DynamicDataSource.class);
beanDefinition.setSynthetic(true);
MutablePropertyValues mpv = beanDefinition.getPropertyValues();
mpv.addPropertyValue("defaultTargetDataSource", defaultDataSource);
mpv.addPropertyValue("targetDataSources", targetDataSources);
registry.registerBeanDefinition("dataSource", beanDefinition);
logger.info("多数据源注册成功");
}
}
没有合适的资源?快使用搜索试试~ 我知道了~
Spring Boot整合Mybatis使用druid实现多数据源自动切换
共91个文件
log:28个
class:14个
java:14个
2星 需积分: 45 91 下载量 112 浏览量
2017-08-24
22:23:22
上传
评论 1
收藏 360KB ZIP 举报
温馨提示
Spring Boot整合Mybatis使用druid实现多数据源自动切换
资源推荐
资源详情
资源评论
收起资源包目录
spring-boot-example.zip (91个子文件)
spring-boot-example
.project 1KB
pom.xml 6KB
target
test-classes
classes
META-INF
maven
spring.boot.example
spring-boot-example
pom.xml 6KB
pom.properties 267B
MANIFEST.MF 3KB
static
888.jpg 47KB
com
test
springboot
dao
StudentMapper.xml 1KB
StudentMapper.class 605B
pojo
Student.class 1KB
HelloApplication.class 1015B
controller
TestController1.class 2KB
TestController2.class 2KB
config
datasource
DynamicDataSourceRegister.class 6KB
DataSourceAspect.class 2KB
DynamicDataSource.class 1KB
TargetDataSource.class 506B
SpringMVC.class 4KB
service
TestService1.class 526B
impl
TestService1Impl.class 2KB
TestService2Impl.class 2KB
TestService2.class 526B
package.xml 2KB
config
logback-spring.xml 9KB
path.properties 21B
application.properties 2KB
templates
student
index1.html 911B
add2.html 2KB
index2.html 910B
add1.html 2KB
.settings
.jsdtscope 597B
org.eclipse.core.resources.prefs 257B
org.eclipse.wst.common.component 785B
org.eclipse.jdt.core.prefs 430B
org.eclipse.wst.common.project.facet.core.xml 296B
org.eclipse.wst.jsdt.ui.superType.container 49B
org.eclipse.m2e.core.prefs 90B
org.eclipse.wst.jsdt.ui.superType.name 6B
src
test
resources
java
main
resources
static
888.jpg 47KB
spring
config
logback-spring.xml 9KB
path.properties 21B
application.properties 1KB
templates
student
index1.html 911B
add2.html 2KB
index2.html 910B
add1.html 2KB
java
com
test
springboot
dao
StudentMapper.xml 1KB
StudentMapper.java 446B
pojo
Student.java 919B
HelloApplication.java 666B
controller
TestController2.java 1KB
TestController1.java 1KB
config
datasource
TargetDataSource.java 508B
DynamicDataSource.java 692B
DataSourceAspect.java 1KB
DynamicDataSourceRegister.java 6KB
SpringMVC.java 3KB
service
TestService1.java 358B
TestService2.java 357B
impl
TestService2Impl.java 1KB
TestService1Impl.java 1KB
webapp
static
666.jpg 47KB
build
package.xml 2KB
.classpath 1KB
logs
spring-boot-example
log_info.log 214KB
log_warn.log 16KB
error
log-error-2017-08-10.0.log 43KB
log-error-2017-08-06.0.log 27KB
log-error-2017-08-09.0.log 92KB
log-error-2017-08-04.0.log 4KB
log-error-2017-08-07.0.log 263KB
log-error-2017-08-08.0.log 90KB
log-error-2017-08-05.0.log 8KB
warn
log-warn-2017-08-05.0.log 980B
log-warn-2017-08-09.0.log 359KB
log-warn-2017-08-10.0.log 161KB
log-warn-2017-08-07.0.log 10KB
log-warn-2017-08-04.0.log 437B
log-warn-2017-08-08.0.log 653KB
log-warn-2017-08-06.0.log 2KB
log_error.log 275KB
info
log-info-2017-08-06.0.log 12KB
log-info-2017-08-04.0.log 152KB
log-info-2017-08-10.0.log 444KB
log-info-2017-08-08.0.log 105KB
log-info-2017-08-05.0.log 30KB
log-info-2017-08-07.0.log 384KB
log-info-2017-08-09.0.log 95KB
SpringBootDemo
log_info.log 5KB
log_warn.log 0B
log_error.log 0B
my.log 53KB
共 91 条
- 1
资源评论
- shushali1232017-09-08骗积分的,真没公德
- iambad2017-09-09不是想要的效果
这个名字想了很久
- 粉丝: 1520
- 资源: 51
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功