springboot多数据源和配置druid连接池
多数据源
1、pom
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.17</version>
</dependency>
2、配置⽂件
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: sql.jdbc.Driver
url: jdbc:mysql://localhost:3306/mytest?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=UTF8
password: root
username: root
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 10
#maxIdle:15
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 320000
validationQuery: SELECT 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
#poolPreparedStatements:true
maxOpenPreparedStatements: 20
3、配置类
import com.alibaba.druid.pool.DruidDataSource;
import org.t.properties.ConfigurationProperties;
import t.annotation.Bean;
import t.annotation.Configuration;
import javax.sql.DataSource;
// druid配置类,读取spring.datasource的相关配置
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid() {
return new DruidDataSource();
}
}
参数说明:
- spring.datasource.druid.max-active  最⼤连接数
- spring.datasource.druid.initial-size  初始化⼤⼩
- spring.datasource.druid.min-idle  最⼩连接数
- spring.datasource.druid.max-wait  获取连接等待超时时间
- spring.datasource.druid.time-between-eviction-runs-millis  间隔多久才进⾏⼀次检测,检测需要关闭的空闲连接,单位是毫秒
- spring.datasource.druid.min-evictable-idle-time-millis  ⼀个连接在池中最⼩⽣存的时间,单位是毫秒
- spring.datasource.druid.filters=config,stat,wall,log4j  配置监控统计拦截的filters,去掉后监控界⾯SQL⽆法进⾏统计,’wall’⽤于防⽕墙多数据源
1、配置⽂件,增加 db2 数据源
查看代码
spring:
datasource:
driver-class-name: sql.jdbc.Driver
url: jdbc:mysql://localhost:3306/mytest?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=UTF8    password: root
username: root
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 10
#maxIdle:15
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 320000
validationQuery: SELECT 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
#poolPreparedStatements:true
maxOpenPreparedStatements: 20
db2:
driver-class-name: sql.jdbc.Driver
url: jdbc:mysql://localhost:3306/demo?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=UTF8      password: root
username: root
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 10
#maxIdle:15
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 320000
validationQuery: SELECT 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
#poolPreparedStatements:true
maxOpenPreparedStatements: 20
2、两个数据源配置类
主数据源配置类:
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
batis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.t.properties.ConfigurationProperties;
import t.annotation.Bean;
import t.annotation.Configuration;
import t.annotation.Primary;
import io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@Configuration
public class DruidConfig {
// 读取配置⽂件中的 spring.datasource配置
// 配置多数据源时要默认⼀个数据源,所以要加 @Primary
@ConfigurationProperties(prefix = "spring.datasource")
@Bean(name = "dataSource")
@Primary
public DataSource dataSource() {
return new DruidDataSource();
}
@Bean(name = "masterTransactionManager")
@Primary
public DataSourceTransactionManager masterTransactionManager() {
return new DataSourceTransactionManager(dataSource());
}
@Bean(name = "masterSqlSessionFactory")
@Primary
public SqlSessionFactory masterSqlSessionFactory(@Qualifier("dataSource") DataSource masterDataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(masterDataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath*:mapper/**/*.xml"));  // 对应的l
sessionFactory.setTypeAliasesPackage("**.domain");          // 对应的实体类,可写可不写
//mybatis 数据库字段与实体类属性驼峰映射配置
Object();
}
@Bean(name = "jdbcTemplate1")
@Primary
public JdbcTemplate jdbcTemplate1() {
return new JdbcTemplate(dataSource());
}
}
第⼆个数据源配置类:
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
batis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.t.properties.ConfigurationProperties;
import t.annotation.Bean;
import t.annotation.Configuration;
import io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@Configuration
public class DruidConfig2 {
// 读取配置⽂件中,spring.datasource.db2 的数据源配置,返加datasource对象
@ConfigurationProperties(prefix = "spring.datasource.db2")
@Bean(name = "dataSource2")
public DataSource dataSource2() {
return new DruidDataSource();
}
@Bean(name = "clusterTransactionManager")
public DataSourceTransactionManager clusterTransactionManager() {
return new DataSourceTransactionManager(dataSource2());
druid连接池配置详解
}
@Bean(name = "clusterSqlSessionFactory")
public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("dataSource2") DataSource masterDataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(masterDataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath*:mapper/**/*.xml"));
sessionFactory.setTypeAliasesPackage("domain");
//mybatis 数据库字段与实体类属性驼峰映射配置
Object();
}
@Bean(name = "jdbcTemplate2")
public JdbcTemplate jdbcTemplate2() {
return new JdbcTemplate(dataSource2());
}
}
以上两个类主要区别是:是否加@Primary注解,读取配置前缀不同,bean的name不⼀样。
3、修改main⽅法上mapper接⼝扫描路径,将对应的mapper接⼝交给相应的数据源 sqlSessionFactoryRef @MapperScan(basePackages = {"com.subject.mapper"},sqlSessionFactoryRef = "masterSqlSessionFactory")
@MapperScan(basePackages = {"com.subject.mapper2"},sqlSessionFactoryRef = "clusterSqlSessio
nFactory")
在包 com.subject.mapper 下的所有mapper接⼝都⾛ masterSqlSessionFactory下的数据源。
在包 com.subject.mapper2 下的所有mapper接⼝都⾛ clusterSqlSessionFactory下的数据源。
注:masterSqlSessionFactory、clusterSqlSessionFactory就是第2步配置类中对应 Factory的bean的name。
druid监控页⾯
在任⼀配置类加⼊以下⽅法,并访问 127.0.0.1:xxxx/druid/index.html /**
*  实现WEB监控的配置处理
*  127.0.0.1:xxxx/druid/index.html
*/
@Bean
public ServletRegistrationBean druidServlet() {
// 现在要进⾏druid监控的配置处理操作
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(                new StatViewServlet(), "/druid/*");
// ⽩名单,多个⽤逗号分割,如果allow没有配置或者为空,则允许所有访问
servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
// ⿊名单,多个⽤逗号分割 (共同存在时,deny优先于allow)
servletRegistrationBean.addInitParameter("deny", "192.168.1.110");
// 控制台管理⽤户名
servletRegistrationBean.addInitParameter("loginUsername", "root");
// 控制台管理密码
servletRegistrationBean.addInitParameter("loginPassword", "root");
// 是否可以重置数据源,禁⽤HTML页⾯上的“Reset All”功能
servletRegistrationBean.addInitParameter("resetEnable", "false");
return servletRegistrationBean ;
}
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean() ;
filterRegistrationBean.setFilter(new WebStatFilter());
//所有请求进⾏监控处理
filterRegistrationBean.addUrlPatterns("/*");
//添加不需要忽略的格式信息
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.css,/druid/*");        return filterRegistrationBean ;
}
以上只是以两个数据源为例,如果有多个,就建多个类

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。