Springboot 整合 Duird

发布于:2025-02-11 ⋅ 阅读:(66) ⋅ 点赞:(0)

1. pom.xml

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

yml配置

  datasource:
    driver-class-name: org.postgresql.Driver
    url: jdbc:postgresql://10.10.11.123:15432/www?currentSchema=sds&useUnicode=true&characterEncoding=UTF-8
    username: sds
    password: ENC(oHWUExwjvp86lWsffZIH4jyDq+g++2ko)
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      initial-size: 10
      min-idle: 10
      max-active: 20
      # 配置获取连接等待超时的时间
      max-wait: 60000
      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      time-between-eviction-runs-millis: 60000
      # 配置一个连接在池中最小生存的时间,单位是毫秒
      min-evictable-idle-time-millis: 600000
      validation-query: SELECT 1 as txt
      filter:
        stat:
          enabled: true
          slow-sql-millis: 2000
      #配置过滤器,过滤掉静态文件
      web-stat-filter:
        enabled: true
        url-pattern: /*
        exclusions: /druid/*,*.js,*.css,*.gif,*.jpg,*.bmp,*.png,*.ico
      #配置可视化控制台页面
      stat-view-servlet:
        enabled: true
        #访问德鲁伊监控页面的地址
        url-pattern: /druid/*
        #IP白名单 没有配置或者为空 则允许所有访问
        allow:
        #IP黑名单 若白名单也存在 则优先使用
        deny:
        #禁用重置按钮
        reset-enable: true
        #登录所用的用户名与密码
        login-username: admin
        login-password: 123123

启动类测试

public class Application implements CommandLineRunner {
	@Autowired
	private DataSource dataSource;

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

	@Override
	public void run(String... args) throws Exception {
		log.info("[run][获得数据源:{}]", dataSource.getClass());
		DruidDataSource dataSource1 = (DruidDataSource) dataSource;
		int maxActive = dataSource1.getMaxActive();
		int minIdle = dataSource1.getMinIdle();
		log.info("[run][最大连接:{}]", maxActive);
		log.info("[run][最小连接:{}]", minIdle);

	}

手动JDBC,执行动态sql

无需再new DataSource(); 直接注入系统默认数据源即可。

public class JdbcTemplateConfig {

    @Autowired
    private DataSource dataSource;

    @Bean
    public JdbcTemplate jdbcTemplate() {
        return new JdbcTemplate(dataSource);
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        DruidDataSource dataSource1 = (DruidDataSource) dataSource;
        int maxActive = dataSource1.getMaxActive();
        int minIdle = dataSource1.getMinIdle();
        log.info("[jdbc][最大连接:{}]", maxActive);
        log.info("[jdbc][最小连接:{}]", minIdle);
        transactionManager.setDataSource(dataSource);
        return transactionManager;
    }
}

启动日志

说明能拿到系统默认的数据库连接池
在这里插入图片描述

Duird 监控地址

地址: http://localhost:8088/pms-busi-service/druid/
在这里插入图片描述

SQL监控

需将sql监控开启

	duird:
      filter:
        stat:
          enabled: true
          slow-sql-millis: 2000

网站公告

今日签到

点亮在社区的每一天
去签到