SpringBoot整合Druid数据连接池

SpringBoot整合Druid数据连接池

Druid是什么?

Druid是Alibaba开源的的数据库连接池。Druid能够提供强大的监控和扩展功能。

在哪里下载druid

maven中央仓库: http://central.maven.org/maven2/com/alibaba/druid/

怎么获取Druid的源码

Druid是一个开源项目,源码托管在github上,源代码仓库地址是 https://github.com/alibaba/druid。同时每次Druid发布正式版本和快照的时候,都会把源码打包,你可以从上面的下载地址中找到相关版本的源码

怎么配置maven

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <!-- 可通过中央仓库获取最新的版本号,这里用我项目中的版本号 -->
    <version>1.0.11</version>
</dependency>

开始配置

  • 首先是 application.properties
# 数据库配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 注:此处必须用 Druid 的数据源
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.name=test
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=10
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=3600000
spring.datasource.minEvictableIdleTimeMillis=3600000
spring.datasource.validationQuery=select ‘x‘
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=true
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.filters=stat,wall,slf4j
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
spring.datasource.useGlobalDataSourceStat=true

# druid 登录信息
druid.config.user-name=root
druid.config.password=root
druid.config.url-mapping=/druid/*
  • 封装数据库配置到 Java Bean
@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
public class DBProperties {
    private String url;
    private String username;
    private String password;
    private String driverClassName;
    private int initialSize;
    private int minIdle;
    private int maxActive;
    private int maxWait;
    private int timeBetweenEvictionRunsMillis;
    private int minEvictableIdleTimeMillis;
    private String validationQuery;
    private boolean testWhileIdle;
    private boolean testOnBorrow;
    private boolean testOnReturn;
    private boolean poolPreparedStatements;
    private int maxPoolPreparedStatementPerConnectionSize;
    private String filters;
    private String connectionProperties;
    private boolean useGlobalDataSourceStat;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public int getInitialSize() {
        return initialSize;
    }

    public void setInitialSize(int initialSize) {
        this.initialSize = initialSize;
    }

    public int getMinIdle() {
        return minIdle;
    }

    public void setMinIdle(int minIdle) {
        this.minIdle = minIdle;
    }

    public int getMaxActive() {
        return maxActive;
    }

    public void setMaxActive(int maxActive) {
        this.maxActive = maxActive;
    }

    public int getMaxWait() {
        return maxWait;
    }

    public void setMaxWait(int maxWait) {
        this.maxWait = maxWait;
    }

    public int getTimeBetweenEvictionRunsMillis() {
        return timeBetweenEvictionRunsMillis;
    }

    public void setTimeBetweenEvictionRunsMillis(int timeBetweenEvictionRunsMillis) {
        this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
    }

    public int getMinEvictableIdleTimeMillis() {
        return minEvictableIdleTimeMillis;
    }

    public void setMinEvictableIdleTimeMillis(int minEvictableIdleTimeMillis) {
        this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
    }

    public String getValidationQuery() {
        return validationQuery;
    }

    public void setValidationQuery(String validationQuery) {
        this.validationQuery = validationQuery;
    }

    public boolean isTestWhileIdle() {
        return testWhileIdle;
    }

    public void setTestWhileIdle(boolean testWhileIdle) {
        this.testWhileIdle = testWhileIdle;
    }

    public boolean isTestOnBorrow() {
        return testOnBorrow;
    }

    public void setTestOnBorrow(boolean testOnBorrow) {
        this.testOnBorrow = testOnBorrow;
    }

    public boolean isTestOnReturn() {
        return testOnReturn;
    }

    public void setTestOnReturn(boolean testOnReturn) {
        this.testOnReturn = testOnReturn;
    }

    public boolean isPoolPreparedStatements() {
        return poolPreparedStatements;
    }

    public void setPoolPreparedStatements(boolean poolPreparedStatements) {
        this.poolPreparedStatements = poolPreparedStatements;
    }

    public int getMaxPoolPreparedStatementPerConnectionSize() {
        return maxPoolPreparedStatementPerConnectionSize;
    }

    public void setMaxPoolPreparedStatementPerConnectionSize(int maxPoolPreparedStatementPerConnectionSize) {
        this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
    }

    public String getFilters() {
        return filters;
    }

    public void setFilters(String filters) {
        this.filters = filters;
    }

    public String getConnectionProperties() {
        return connectionProperties;
    }

    public void setConnectionProperties(String connectionProperties) {
        this.connectionProperties = connectionProperties;
    }

    public boolean isUseGlobalDataSourceStat() {
        return useGlobalDataSourceStat;
    }

    public void setUseGlobalDataSourceStat(boolean useGlobalDataSourceStat) {
        this.useGlobalDataSourceStat = useGlobalDataSourceStat;
    }

}
@Configuration
@ConfigurationProperties(prefix = "druid.config")
public class DruidProperties {

    private String userName;

    private String password;

    private String urlMapping;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUrlMapping() {
        return urlMapping;
    }

    public void setUrlMapping(String urlMapping) {
        this.urlMapping = urlMapping;
    }
}
  • 配置数据源
/**
 * 持久层相关配置
 */
@Configuration
public class SessionFactoryConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(SessionFactoryConfig.class);

    private final DBProperties db;

    @Autowired
    public SessionFactoryConfig(DBProperties db) {
        this.db = db;
    }

    /**
     * 创建数据源
     */
    @Bean
    // 如果访问 Druid 时数据源页面显示 (*) property for user to setup 可用下面的 Bean 注入方式
    // @Bean(destroyMethod = "close", initMethod = "init")
    @Primary
    public DataSource dataSource() {
        final DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(db.getUrl());
        datasource.setUsername(db.getUsername());
        datasource.setPassword(db.getPassword());
        datasource.setDriverClassName(db.getDriverClassName());
        datasource.setInitialSize(db.getInitialSize());
        datasource.setMinIdle(db.getMinIdle());
        datasource.setMaxActive(db.getMaxActive());
        datasource.setMaxWait(db.getMaxWait()); datasource.setTimeBetweenEvictionRunsMillis(db.getTimeBetweenEvictionRunsMillis());
        datasource.setMinEvictableIdleTimeMillis(db.getMinEvictableIdleTimeMillis());
        datasource.setValidationQuery(db.getValidationQuery());
        datasource.setTestOnReturn(db.isTestOnReturn());
        datasource.setPoolPreparedStatements(db.isPoolPreparedStatements());
        datasource.setMaxPoolPreparedStatementPerConnectionSize(db.getMaxPoolPreparedStatementPerConnectionSize());
        datasource.setUseGlobalDataSourceStat(db.isUseGlobalDataSourceStat());
        try {
            datasource.setFilters(db.getFilters());
        } catch (SQLException e) {
            LOGGER.info("druid configuration initialization filter: " + e);
        }
        datasource.setConnectionProperties(db.getConnectionProperties());
        return datasource;
    }
}
  • Druid连接池配置
/**
 * Druid连接池配置
 */
@Configuration
public class DruidConfiguration {

    private static final Logger LOGGER = LoggerFactory.getLogger(DruidConfiguration.class);

    private final DruidProperties druidProperties;

    @Autowired
    public DruidConfiguration(DruidProperties dp) {
        this.druidProperties = dp;
    }

    /**
     * 访问路径及用户名、密码
     */
    @Bean
    public ServletRegistrationBean druidConfig() {
        LOGGER.info("init Druid Servlet Configuration ");
        final ServletRegistrationBean srb = new ServletRegistrationBean();
        srb.setServlet(new StatViewServlet());
        LOGGER.info("Druid Config Info --> {}", druidProperties);
        srb.addUrlMappings(druidProperties.getUrlMapping());
        srb.addInitParameter("loginUsername", druidProperties.getUserName());
        srb.addInitParameter("loginPassword", druidProperties.getPassword());
        return srb;
    }

    /**
     * 配置过滤器
     */
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        final FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
}
  • 委托Druid进行Spring 监控
/**
 * 委托Druid进行Spring 监控
 */
@Configuration
public class SpringMonitoringConfig {

    @Bean(name = "druid-stat-interceptor")
    public DruidStatInterceptor druidStatInterceptor() {
        return new DruidStatInterceptor();
    }

    @Bean(name = "druid-stat-pointcut")
    // 非单例
    @Scope("prototype")
    public JdkRegexpMethodPointcut druidStatPointcut() {
        final JdkRegexpMethodPointcut pointcut = new JdkRegexpMethodPointcut();
        pointcut.setPatterns("com.ajm.punch_the_clock.controller.*", "com.ajm.punch_the_clock.mapper.*");
        return pointcut;
    }

    @Bean
    public DefaultPointcutAdvisor druidStatAdvisor(@Qualifier("druid-stat-interceptor") final DruidStatInterceptor druidStatInterceptor,
                                                   @Qualifier("druid-stat-pointcut") final JdkRegexpMethodPointcut druidStatPointcut) {
        final DefaultPointcutAdvisor defaultPointAdvisor = new DefaultPointcutAdvisor();
        defaultPointAdvisor.setPointcut(druidStatPointcut);
        defaultPointAdvisor.setAdvice(druidStatInterceptor);
        return defaultPointAdvisor;
    }

}
  • 项目启动,访问 http://127.0.0.1:端口号/druid

如果出现以上页面,恭喜你。整合 OK :-)

原文地址:https://www.cnblogs.com/yliucnblogs/p/10243607.html

时间: 2024-10-27 10:54:56

SpringBoot整合Druid数据连接池的相关文章

【Mysql】SpringBoot阿里Druid数据源连接池配置

一.pom.xml添加 <!-- 配置数据库连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.0</version> </dependency> 二.application.properties 添加 # 连接池配置spring.datasource.type

Springboot整合Druid数据源

Druid是阿里巴巴的一个开源的JDBC组件,该组件由数据库连接池.插件框架和SQL解析器组成,主要功能如下: 1.DruidDriver 代理Driver,能够提供基于Filter-Chain模式的插件体系. 2.DruidDataSource 高效可管理的数据库连接池. 3.SQLParser解析器兼容所有的JDBC数据库,如:Mysql,Oracle.SQL Server数据库. 同时它结合了C3P0.DBCP.PROXOOL等DB池的优点,加入了日志监控,在稳定性.可扩展性和性能方便具有

Springboot整合druid

概述 前面的Springboot整合jdbcTemplate.mybatis.jpa三篇文章中使用的数据库连接池都是Spingboot默认配置的tomcat.jdbc.pool.配置原理进入org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration类查看,根据通过spring.datasource.type配置其他连接池,当然我们也可以配置指定的数据库连接池比如Druid.配置Druid有两种方式 第一种 配置传统的Dr

Hibernate整合C3P0实现连接池&lt;转&gt;

Hibernate整合C3P0实现连接池 Hibernate中可以使用默认的连接池,无论功能与性能都不如C3PO(网友反映,我没有测试过),C3P0是一个开源的JDBC连接池,它实 现了数据源和JNDI绑定,支持JDBC3规范和JDBC2的标准扩展.目前使用它的开源项目有Hibernate,Spring等. C3P0是一个易于使用JDBC3规范和JDBC2可选的扩展定义的功能增强,使传统的JDBC驱动程序“enterprise-ready”库. 特别是C3P0提供了一些有用的服务:适应传统的基于

c3p0,dbcp与druid 三大连接池的区别[转]

说到druid,这个是在开源中国开源项目中看到的,说是比较好的数据连接池.于是乎就看看.扯淡就到这. 下面就讲讲用的比较多的数据库连接池.(其实我最先接触的是dbcp这个) 1)DBCP DBCP是一个依赖Jakarta commons-pool对象池机制的数据库连接池.DBCP可以直接的在应用程序中使用,Tomcat的数据源使用的就是DBCP. 2)c3p0 c3p0是一个开放源代码的JDBC连接池,它在lib目录中与Hibernate一起发布,包括了实现jdbc3和jdbc2扩展规范说明的C

Netbeans 中创建数据连接池和数据源步骤

1.启动glassfish服务器, 在浏览器的地址栏中输入 http://localhost:4848 2.首先建立JDBC Connection Pools: 3.new 一个Connectio Pools 4.对General Settings属性填写: 5.填写Datasource Classname:com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource Ping属性选中,可以用来检验数据连接池是否创建成功! . 6.对Ad

记录一个简单的dbcp数据连接池

这个示例用到了ThreadLocal与dbcp,我觉得有点意思,就整理了下.使用dbcp,肯定要导入commons-dbcp.jar包.下面直接贴DBUtil代码: public class DBUtil { private static DataSource ds; //定义一个数据连接池 //threadLocal是线程的局部变量,它的实例通常是类中的 private static 字段 private static ThreadLocal<Connection> connLocal=ne

数据连接池JNDI

数据库连接有很多中方式,JDBC数据库的连接方式,前边我们已经介绍过了,而开发中我们经常使用的是DataBaseConnectionPool(数据库连接池,DBCP).数据库连接池到底是什么?它比jdbc数据库连接有什么优势呢?它又怎么使用呢? 一,先看一下JDBC连接,每次用户访问数据库时,需要JDBC为我们创建数据库连接,我们使用,然后关闭.而当我们加断点测试,可以发现这个过程中创建数据库连接这个过程是比较费时间的,而不是我们在数据库中操作数据费时间.所以JDBC这种方式的效率大大折扣.而且

jdk 动态代理 数据连接池

package com.itheima.datasource; import java.io.PrintWriter; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayL