springboot 整合阿里 Druid 数据库连接池

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012946310/article/details/82318439

一,Druid是什么?

Druid是Java语言中最好的数据库连接池。Druid能够提供强大的监控和扩展功能。

二, 在哪里下载druid

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

三, 怎么获取Druid的源码

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

四,springboot 整合 Druid 连接池

环境描述:springboot 2.0.4.RELEASE 与 jdk1.8
1,新建 springboot 项目:
File –> NEW –> Project –> 选择Spring Initializr –> Next 输入 maven grpup 和 Artifact
这里写图片描述
输入后点击 Next 选择我们项目所需要的快速启动maven依赖,如下图:
这里写图片描述
Lombok介绍:可以减少很多重复代码的书写。比如说getter/setter/toString等方法的编写,需要安装插件,不懂得可以参考文章:https://blog.csdn.net/u012946310/article/details/82348669
随后在点击 Next –> Finish

2,加入阿里系的Druid依赖包:

<!-- 阿里系的Druid依赖包 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.9</version>
</dependency>
<!-- Druid 依赖 log4j包 -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

3,在 application.properties 文件中加入数据库的配置:

#mysql 配置
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.2.126:3306/springboot_druid_demo?characterEncoding=utf-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456

#阿里druid连接池驱动配置信息
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#连接池的配置信息
#初始化大小,最小,最大
spring.datasource.initialSize=2
spring.datasource.minIdle=2
spring.datasource.maxActive=3
#配置获取连接等待超时的时间
spring.datasource.maxWait=6000
#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
#配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
#打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
#配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.filters=stat,wall,log4j
#通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

4,加入驱动配置类:
由于目前Spring Boot中默认支持的连接池只有 dbcp、dbcp2、 tomcat、hikari 连接池,Druid 暂时不在Spring Boot 中的直接支持,故需要进行配置信息的定制:
新建druid包,加入DruidDBConfig 实现类
DruidDBConfig 类:

package springboot_druid_demo.druid;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.SQLException;

@Configuration
public class DruidDBConfig {

    private static final Logger logger = LoggerFactory.getLogger(DruidDBConfig.class);

    private static final String DB_PREFIX = "spring.datasource";

    @Bean
    public ServletRegistrationBean druidServlet() {
        logger.info("init Druid Servlet Configuration ");
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        // IP白名单
        servletRegistrationBean.addInitParameter("allow", "");
        // IP黑名单(共同存在时,deny优先于allow)
        servletRegistrationBean.addInitParameter("deny", "");
        //控制台管理用户
        servletRegistrationBean.addInitParameter("loginUsername", "");
        servletRegistrationBean.addInitParameter("loginPassword", "");
        //是否能够重置数据 禁用HTML页面上的“Reset All”功能
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }

    // 解决 spring.datasource.filters=stat,wall,log4j 无法正常注册进去
    @ConfigurationProperties(prefix = DB_PREFIX)
    class IDataSourceProperties {
        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;

        @Bean     //声明其为Bean实例
        @Primary  //在同样的DataSource中,首先使用被标注的DataSource
        public DataSource dataSource() {
            DruidDataSource datasource = new DruidDataSource();
            datasource.setUrl(url);
            datasource.setUsername(username);
            datasource.setPassword(password);
            datasource.setDriverClassName(driverClassName);

            //configuration
            datasource.setInitialSize(initialSize);
            datasource.setMinIdle(minIdle);
            datasource.setMaxActive(maxActive);
            datasource.setMaxWait(maxWait);
            datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
            datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
            datasource.setValidationQuery(validationQuery);
            datasource.setTestWhileIdle(testWhileIdle);
            datasource.setTestOnBorrow(testOnBorrow);
            datasource.setTestOnReturn(testOnReturn);
            datasource.setPoolPreparedStatements(poolPreparedStatements);
            datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
            try {
                datasource.setFilters(filters);
            } catch (SQLException e) {
                System.err.println("druid configuration initialization filter: " + e);
            }
            datasource.setConnectionProperties(connectionProperties);
            return datasource;
        }

        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;
        }
    }

}

加入 DruidDBConfig 类后 Druid 的配置信息就算配置完成了,接下来加入model、service、mapper 测试 Druid 连接池的结果。

5,加入model、service、mapper 等类进行连接池测试:
User 类:

package springboot_druid_demo.model;

import lombok.Data;

@Data
public class User {

    private Integer userId;

    private String userName;

    private String userPhone;

    private String userAddress;

}

UserMapper 类:

package springboot_druid_demo.mappers;


import springboot_druid_demo.model.User;

public interface UserMapper {

    int deleteByPrimaryKey(Integer var1);

    int insertSelective(User var1);

    User selectByPrimaryKey(Integer var1);

}

UserService 类:

package springboot_druid_demo.service;


import springboot_druid_demo.model.User;

public interface UserService {

    int deleteByPrimaryKey(Integer var1);

    int insertSelective(User var1);

    User selectByPrimaryKey(Integer var1);

}

UserServiceImpl 类:

package springboot_druid_demo.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import springboot_druid_demo.mappers.UserMapper;
import springboot_druid_demo.model.User;
import springboot_druid_demo.service.UserService;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public int deleteByPrimaryKey(Integer var1) {
        return userMapper.deleteByPrimaryKey(var1);
    }

    @Override
    public int insertSelective(User var1) {
        return userMapper.insertSelective(var1);
    }

    @Override
    public User selectByPrimaryKey(Integer var1) {
        return userMapper.selectByPrimaryKey(var1);
    }
}

UserMapper.xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="springboot_druid_demo.mappers.UserMapper">

    <delete id="deleteByPrimaryKey">
        DELETE
        FROM user
        WHERE user_id = #{userId}
    </delete>

    <insert id="insertSelective">
        INSERT INTO user (
          user_name, user_phone, user_address
        )
        VALUES
          (
            #{userName}, #{userPhone}, #{userAddress}
          )
    </insert>

    <resultMap id="selectByPrimaryKeyMap" type="springboot_druid_demo.model.User">
        <result column="user_id" property="userId"/>
        <result column="user_name" property="userName"/>
        <result column="user_phone" property="userPhone"/>
        <result column="user_address" property="userAddress"/>
    </resultMap>
    <select id="selectByPrimaryKey" parameterType="int" resultMap="selectByPrimaryKeyMap">
      select *
      from user
      where user_id = #{userId}
    </select>

</mapper>

6,以上类加入成功后还需要添加 mybatis 的一些配置:

  • 在 application.properties 配置文件中加入 mappers 的 xml 文件夹扫描配置:
#mapper文件目录
mybatis.mapper-locations=classpath*:mappers/*.xml
  • 在 springboot 的 Application 启动类中加入
@MapperScan("springboot_druid_demo.mappers") // 扫码mapper包

注解,表示扫描的 mapper 包的所在位置,添加的结果如下所示
这里写图片描述
7,整合 swagger 方便接口的测试与效果展示:
整合 swagger 参照博客:https://blog.csdn.net/u012946310/article/details/82353202

8,整合结果展示:
分别访问地址:
http://localhost:8080/swagger-ui.html

http://localhost:8080/druid/index.html
就可以查看到我们的接口地址与 druid 监控控制台
这里写图片描述
运行相应的 sql 后 druid 就会监控到了。

9,安全设置:
如果需要加上登陆用户密码,只需要在上面代码

// 控制台管理用户
servletRegistrationBean.addInitParameter("loginUsername", "");
servletRegistrationBean.addInitParameter("loginPassword", "");

里面填入自己的用户名和密码就可以了。

最后贴上此demo git 地址:https://gitee.com/hwm0717/springboot_druid_demo.git

猜你喜欢

转载自blog.csdn.net/u012946310/article/details/82318439