微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SpringBoot怎么使用druid配置多数据源

这篇“SpringBoot怎么使用druid配置多数据源文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“SpringBoot怎么使用druid配置多数据源文章吧。

一、背景

使用spring boot配置多数据源,数据源分别为postgresqlmysql

二、版本介绍

  • spring boot——2.5.4

  • druid——1.2.11

  • postgresql——12

  • MysqL——8.0.16

  • maven——3.0

  • idea——2019

三、项目结构

java package目录

SpringBoot怎么使用druid配置多数据源

resource目录存放mapper.xml文件,按照数据源创建package 

 

SpringBoot怎么使用druid配置多数据源

四、maven依赖 

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.11</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- MysqL驱动 -->
        <dependency>
            <groupId>MysqL</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

五、yaml配置文件

server:
  port: 8081
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      web-stat-filter:
        enabled: true #是否启用StatFilter认值true
        url-pattern: /*
        exclusions: /druid/*,*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico
        session-stat-enable: true
        session-stat-max-count: 10
      stat-view-servlet:
        enabled: true #是否启用StatViewServlet认值true
        url-pattern: /druid/*
        reset-enable: true
        login-username: admin
        login-password: admin
        allow:
 
      db1:
        username: postgres
        password: localhost
        url: jdbc:postgresql://localhost:5432/test
        driver-class-name: org.postgresql.Driver
        initial-size: 5  # 初始化大小
        min-idle: 5  # 最小
        max-active: 100  # 最大
        max-wait: 60000  # 配置获取连接等待超时的时间
        validation-query: select version()
        time-between-eviction-runs-millis: 60000  # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
        min-evictable-idle-time-millis: 300000  # 指定一个空闲连接最少空闲多久后可被清除,单位是毫秒
        filters: config,wall,stat  # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
        # 通过connectProperties属性来打开mergesql功能;慢sql记录
        connectionProperties: druid.stat.slowsqlMillis=200;druid.stat.logSlowsql=true;config.decrypt=false
        test-while-idle: true
        test-on-borrow: true
        test-on-return: false
        # 是否缓存preparedStatement,也就是PSCache  官方建议MysqL下建议关闭   个人建议如果想用sql防火墙 建议打开
        pool-prepared-statements: true
        max-pool-prepared-statement-per-connection-size: 20
 
      db2:
        username: root
        password: localhost
        url: jdbc:MysqL://localhost:3306/springboot?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=Asia/Shanghai
        driver-class-name: com.MysqL.cj.jdbc.Driver
        initial-size: 5  # 初始化大小
        min-idle: 5  # 最小
        max-active: 100  # 最大
        max-wait: 60000  # 配置获取连接等待超时的时间
        validation-query: select 'x'
        time-between-eviction-runs-millis: 60000  # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
        min-evictable-idle-time-millis: 300000  # 指定一个空闲连接最少空闲多久后可被清除,单位是毫秒
        filters: config,wall,stat  # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
        # 通过connectProperties属性来打开mergesql功能;慢sql记录
        connectionProperties: druid.stat.slowsqlMillis=200;druid.stat.logSlowsql=true;config.decrypt=false
        test-while-idle: true
        test-on-borrow: true
        test-on-return: false
        # 是否缓存preparedStatement,也就是PSCache  官方建议MysqL下建议关闭   个人建议如果想用sql防火墙 建议打开
        pool-prepared-statements: true
        max-pool-prepared-statement-per-connection-size: 20
 
mybatis:
  mapper-locations: classpath:com/demo/mapper/*.xml
  type-aliases-package: com.demo.entity
  configuration:
    log-impl:
    mapUnderscoreToCamelCase: true
 
#showsql
logging:
  level:
    java.sql: debug
    org.apache.ibatis: debug
    com.demo.mapper: debug
  config: classpath:logback-spring.xml

六、数据源配置文件

@Configuration
@MapperScan(basePackages = "com.demo.mapper.postgre.**", sqlSessionFactoryRef = "onesqlSessionFactory")
public class DataSourceConfig1 {
    // 将这个对象放入spring容器中
    @Bean(name = "oneDataSource")
    // 表示这个数据源是认数据源
    @Primary
    // 读取application.properties中的配置参数映射成为一个对象
    // prefix表示参数的前缀
    @ConfigurationProperties(prefix = "spring.datasource.druid.db1")
    public DataSource getDateSource1() {
        return DataSourceBuilder.create().type(DruidDataSource.class).build();
    }
 
    @Bean(name = "onesqlSessionFactory")
    // 表示这个数据源是认数据源
    @Primary
    // @Qualifier表示查找spring容器中名字为oneDataSource的对象
    public sqlSessionFactory onesqlSessionFactory(@Qualifier("oneDataSource") DataSource datasource)
            throws Exception {
        sqlSessionfactorybean bean = new sqlSessionfactorybean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                // 设置mybatis的xml所在位置
                new PathMatchingResourcePatternResolver().getResources("classpath*:com.demo.mapper.postgre/*.xml"));
        return bean.getobject();
    }
 
    @Bean("onesqlSessionTemplate")
    // 表示这个数据源是认数据源
    @Primary
    public sqlSessionTemplate onesqlSessionTemplate(
            @Qualifier("onesqlSessionFactory") sqlSessionFactory sessionFactory) {
        return new sqlSessionTemplate(sessionFactory);
    }
 
}
@Configuration
@MapperScan(basePackages = "com.demo.mapper.MysqL", sqlSessionFactoryRef = "twosqlSessionFactory")
public class DataSourceConfig2 {
    // 将这个对象放入spring容器中
    @Bean(name = "twoDataSource")
    // 读取application.properties中的配置参数映射成为一个对象
    // prefix表示参数的前缀
    @ConfigurationProperties(prefix = "spring.datasource.druid.db2")
    public DataSource getDateSource1() {
        return DataSourceBuilder.create().type(DruidDataSource.class).build();
    }
 
    @Bean(name = "twosqlSessionFactory")
    // 表示这个数据源是认数据源
    //@Primary
    // @Qualifier表示查找spring容器中名字为oneDataSource的对象
    public sqlSessionFactory onesqlSessionFactory(@Qualifier("twoDataSource") DataSource datasource)
            throws Exception {
        sqlSessionfactorybean bean = new sqlSessionfactorybean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                // 设置mybatis的xml所在位置
                new PathMatchingResourcePatternResolver().getResources("classpath*:com.demo.mapper.MysqL/*.xml"));
        return bean.getobject();
    }
 
    @Bean("twosqlSessionTemplate")
    // 表示这个数据源是认数据源
    //@Primary
    public sqlSessionTemplate onesqlSessionTemplate(
            @Qualifier("twosqlSessionFactory") sqlSessionFactory sessionFactory) {
        return new sqlSessionTemplate(sessionFactory);
    }
 
}

七、启动类配置

关键点:去除  exclude = {DataSourceAutoConfiguration.class} 及扫描 com.demo.mapper目录

@MapperScan("com.demo.mapper")
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class DemoApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication .class, args);
    }
}

八、druid管理页面

输入地址 localhost://8081/druid,输入 admin/admin     

以上就是关于“SpringBoot怎么使用druid配置多数据源”这篇文章内容,相信大家都有了一定的了解,希望小编分享内容对大家有帮助,若想了解更多相关的知识内容,请关注编程之家行业资讯频道。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐