四.Springboot+Mybatis+Alibaba Druid连接池(多数据源配置)

2 篇文章 0 订阅
1 篇文章 0 订阅

“Druid连接池是阿里巴巴开源你的数据库连接池项目。Druid连接池为监控而生,内置强大的监控功能,监控特性不影响性能。功能强大,能防SQL注入,内置Logging能诊断Hack应用行为。”
—Alibaba Druid官方介绍


druid官方 git地址:https://github.com/alibaba/druid
druid官方中文文档:https://github.com/alibaba/druid/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98

一.添加pom依赖

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.10</version>
    </dependency>

二.数据源配置

通过druid-spring-boot-starter,可直接把druid配置信息注入到spring.datasource.druid下

  1. db1数据源配置
#----DS1----
spring.datasource.db1.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.db1.url=jdbc:mysql://127.0.0.1:3306/demo
spring.datasource.db1.username=root
spring.datasource.db1.password=trsadmin
mybatis.mapper-locations1=classpath:mappings1/*.xml
  1. db2数据源配置
#----DS2---
spring.datasource.db2.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.db2.url=jdbc:mysql://127.0.0.1:3306/demo2
spring.datasource.db2.username=root
spring.datasource.db2.password=trsadmin
mybatis.mapper-locations2=classpath:mappings2/*.xml
  1. druid配置

#druid配置
spring.datasource.type = com.alibaba.druid.pool.DruidDataSource
#初始化连接数
spring.datasource.druid.initial-size = 5
#最大连接数
spring.datasource.druid.max-active = 20
#最小连接数
spring.datasource.druid.min-idle = 5
#最大连接事件 单位毫秒
spring.datasource.druid.max-wait= 30000


# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.druid.pool-prepared-statements=true
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20
#spring.datasource.druid.max-open-prepared-statements= #和上面的等价
spring.datasource.druid.validation-query=SELECT 1 FROM DUAL
spring.datasource.druid.validation-query-timeout=30000
#是否在获得连接后检测其可用性
spring.datasource.druid.test-on-borrow=true
#是否在连接放回连接池后检测其可用性
spring.datasource.druid.test-on-return=true
#是否在连接空闲一段时间后检测其可用性
spring.datasource.druid.test-while-idle=true

#注:druid如果不配置Filter,默认是开启的,譬如web-stat-filter、stat-view-servlet等,可以通过配置属性覆盖默认配置,例如:
# WebStatFilter monitor
spring.datasource.druid.web-stat-filter.enabled=true
spring.datasource.druid.web-stat-filter.url-pattern= /*
spring.datasource.druid.web-stat-filter.exclusions= *.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*
spring.datasource.druid.web-stat-filter.session-stat-enable= false
spring.datasource.druid.web-stat-filter.session-stat-max-count= 1000
spring.datasource.druid.web-stat-filter.profile-enable=true

# StatViewServlet ,it configs who can visit
#如果设置了StatViewServlet,即配置了监控池认证,
#要进监控池需要输入http://127.0.0.1:8083/druid/login.html,
#如果没配置,直接输入http://127.0.0.1:8083/druid/即可
spring.datasource.druid.stat-view-servlet.enabled= true
spring.datasource.druid.stat-view-servlet.url-pattern= /druid/*
spring.datasource.druid.stat-view-servlet.reset-enable= true
spring.datasource.druid.stat-view-servlet.login-username= admin
spring.datasource.druid.stat-view-servlet.login-password= admin1234
spring.datasource.druid.stat-view-servlet.allow= 127.0.0.1

三.SpringBoot配置多数据源

  1. db1数据源
package com.xjb.data.provider.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * 多数据源配置 druid
 * Created by xjb on 2019/3/6
 **/
@Configuration
//basePackages属性配置需要扫描的mybatis的mapper文件位置,sqlSessionFactory属性配置具体的 sqlSessionFactory.
@MapperScan(basePackages = "com.xjb.data.provider.mapper.db1", sqlSessionTemplateRef = "db1SqlSessionTemplate")
@Slf4j
public class DataSource1Config {

    //mybatis 配置文件路径
    @Value("${mybatis.mapper-locations1}")
    private String mapper_locations = "";

    @Bean
    //ConfigurationProperties读取并且设置我们在application.properties配置的内容.
    @ConfigurationProperties(prefix = "spring.datasource.db1")
    //@Primary这个注解用来标识当存在多个相同的类型的bean时,优先选用哪个bean注入,
    // 需要注意的是,配置多数据源的时候,必须有一个且只能有一个@Primary注解
    @Primary
    public DataSource db1DataSource() {

        //之前使用的DataSourceBuilder.create().build()
        //导致spring.datasource.druid.*配置的属性都没有生效
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapper_locations));
        return bean.getObject();
    }

    @Bean
    @Primary
    public DataSourceTransactionManager db1TransactionManager(@Qualifier("db1DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    @Primary
    public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

  1. db2数据源配置
package com.xjb.data.provider.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * Created by xjb on 2019/3/6
 **/
@Configuration
@MapperScan(basePackages = "com.xjb.data.provider.mapper.db2", sqlSessionTemplateRef = "db2SqlSessionTemplate")
public class DataSource2Config {
    @Value("${mybatis.mapper-locations2}")
    private String mapper_locations = "";

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.db2")
    public DataSource db2DataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    public SqlSessionFactory db2SqlSessionFactory(@Qualifier("db2DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapper_locations));
        return bean.getObject();
    }

    @Bean
    public DataSourceTransactionManager db2TransactionManager(@Qualifier("db2DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public SqlSessionTemplate db2SqlSessionTemplate(@Qualifier("db2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

四.mapper文件配置目录

在这里插入图片描述
配置完成后启动应用进入 http://localhost:端口号/druid/index.html 就可以查看druid的监控池了

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值