springboot使用dynamic-datasource和druid配置多数据库连接及druid监控

该文章介绍了如何在SpringBoot应用中集成DynamicDataSource和Druid数据源管理工具,包括添加相关依赖、配置多数据源(如PostgreSQL和Clickhouse)以及Druid的详细配置参数,如连接池大小、监控等。

一、首先需要引入的jar包

<dependency>
	<groupId>com.baomidou</groupId>
	<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
	<version>3.2.0</version>
</dependency>
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid-spring-boot-starter</artifactId>
	<version>1.2.6</version>
</dependency>

二、spring yaml的配置,注意druid的缩进,错了不起作用

spring:
  autoconfigure:
    exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure
  datasource:
    dynamic:
      primary: postgresql  # 配置默认数据库
      strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
      datasource:
        postgresql:
          url: jdbc:postgresql://127.0.0.1:5432/postgres?stringtype=unspecified
          username: postgres
          password: admin123
          driver-class-name: org.postgresql.Driver
          druid:
            initial-size: 10
            min-idle: 10
            max-active: 500
            max-wait: 60000
            time-between-eviction-runs-millis: 60000
            min-evictable-idle-time-millis: 300000
        clickhouse:
          url: jdbc:clickhouse://127.0.0.1:8123/default
          username: default
          password: admin123
          driver-class-name: ru.yandex.clickhouse.ClickHouseDriver
          druid:
            initial-size: 50
            min-idle: 50
            max-active: 2000
            max-wait: 120000
            time-between-eviction-runs-millis: 120000
            min-evictable-idle-time-millis: 600000
      druid:
        test-while-idle: false
        test-on-borrow: false
        test-on-return: false
        pool-prepared-statements: true
        filters: stat,wall,log4j2
    druid:
      web-stat-filter:
        enabled: true
        url-pattern: /*
        exclusions: /druid/*,*.js,*.gif,*.jpg,*.png,*.css,*.ico
      stat-view-servlet:
        enabled: true
        url-pattern: /druid/*
        reset-enable: false
        login-username: admin
        login-password: admin123
        # StatViewSerlvet展示出来的监控信息比较敏感,是系统运行的内部情况,如果你需要做访问控制,可以配置allow和deny这两个参数
        # deny优先于allow,如果在deny列表中,就算在allow列表中,也会被拒绝。如果allow没有配置或者为空,则允许所有访问
        # 配置的格式
        # <IP>
        # 或者<IP>/<SUB_NET_MASK_size>其中128.242.127.1/24
        # 24表示,前面24位是子网掩码,比对的时候,前面24位相同就匹配,不支持IPV6。
        allow:
        deny:

三、下面是druid的其它配置参数,可以参考

spring:
  # 配置数据库信息
  datasource:
    # 数据源配置
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8&characterEncoding=UTF-8&useSSL=false
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    # druid相关配置
    druid:
      # 初始化 最小 最大
      initial-size: 5
      min-idle: 5
      max-active: 20
      # 配置获取连接等待超时的时间
      max-wait: 60000
      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      time-between-eviction-runs-millis: 60000
      # 配置一个连接在池中最小生存的时间,单位是毫秒
      min-evictable-idle-time-millis: 300000
      validation-query: SELECT 'x'
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      # 打开PSCache,并且指定每个连接上PSCache的大小
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 20
      # 配置多个英文逗号分隔
      filters: stat,wall
      # WebStatFilter配置,说明请参考Druid Wiki,配置_配置WebStatFilter
      # 是否启用StatFilter默认值true
      web-stat-filter:
        enabled: true
        url-pattern: /*
        exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
        session-stat-enable: false
        session-stat-max-count: 1000
        principal-cookie-name: admin
        principal-session-name: admin
        profile-enable: true
      # 根据配置中的url-pattern来访问内置监控页面,如果是上面的配置,内置监控页面的首页是/druid/index.html
      # http://loacalhsot:8081/druid
      stat-view-servlet:
        url-pattern: /druid/*  # 监控页面访问路径
        # 允许清空统计数据
        reset-enable: true
        login-username: admin
        login-password: 123456
        # StatViewSerlvet展示出来的监控信息比较敏感,是系统运行的内部情况,如果你需要做访问控制,可以配置allow和deny这两个参数
        # deny优先于allow,如果在deny列表中,就算在allow列表中,也会被拒绝。如果allow没有配置或者为空,则允许所有访问
        # 配置的格式
          # <IP>
          # 或者<IP>/<SUB_NET_MASK_size>其中128.242.127.1/24
          # 24表示,前面24位是子网掩码,比对的时候,前面24位相同就匹配,不支持IPV6。
        allow:
        deny:

### Spring Boot使用 Druid 实现动态数据源 #### Maven 依赖配置 为了在 Spring Boot 项目中实现动态数据源管理,需引入特定的 Maven 依赖项。这些依赖不仅包含了用于连接池功能的 `druid-spring-boot-starter`,还加入了支持多数据源切换逻辑的组件 `dynamic-datasource-spring-boot-starter`。 ```xml <dependencies> <!-- 数据库连接--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency> <!-- 动态数据源 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>dynamic-datasource-spring-boot-starter</artifactId> <version>3.5.1</version> </dependency> </dependencies> ``` #### 主数据源配置类 (MasterDataSourceConfig.java) 主数据源作为默认的数据访问入口,在应用程序启动时会被优先加载并初始化。通过继承自 `AbstractRoutingDataSource` 的方式来定义主数据源的具体参数设置。 ```java @Configuration public class MasterDataSourceConfig { @Bean(name = "masterDataSource") @ConfigurationProperties(prefix = "spring.datasource.master") public DataSource masterDataSource() { return new DruidDataSource(); } } ``` #### 多数据源注册与路由策略设定 除了指定主数据源外,还需声明其他可能用到的次级数据源,并将其加入到全局上下文中以便于后续操作。同时,应制定一套合理的数据源选择机制,确保每次请求都能被导向至合适的数据库实例上执行查询或更新动作。 ```java @Configuration @EnableTransactionManagement @MapperScan(basePackages = {"com.example.mapper"}, sqlSessionFactoryRef="sqlSessionFactory") public class DynamicDataSourceConfig { @Autowired private List<Object> dataSourceList; @Primary @Bean(name = "dataSource") public DynamicDataSource dataSource(@Qualifier("masterDataSource") DataSource masterDataSource, @Qualifier("slaveDataSource") DataSource slaveDataSource) { Map<Object, Object> targetDataSources = new HashMap<>(); targetDataSources.put(DataSourceEnum.MASTER.name(), masterDataSource); targetDataSources.put(DataSourceEnum.SLAVE.name(), slaveDataSource); DynamicDataSource dynamicDataSource = new DynamicDataSource(); dynamicDataSource.setTargetDataSources(targetDataSources); // 添加 N 个数据源 dynamicDataSource.setDefaultTargetDataSource(masterDataSource); // 默认数据源 return dynamicDataSource; } ... } ``` #### 应用属性文件中的数据源配置 (`application.yml`) 最后一步是在应用配置文件内补充各个数据源的相关细节信息,比如 URL、用户名以及密码等必要字段。这里采用 YAML 格式的配置文档来进行表述: ```yaml spring: datasource: type: com.alibaba.druid.pool.DruidDataSource master: url: jdbc:mysql://localhost:3306/master_db?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver slave: url: jdbc:mysql://localhost:3307/slave_db?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver ``` 上述方法能够有效帮助开发者快速搭建起具备高可用性灵活性特点的企业级 Java Web 应用程序[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值