springboot整合Druid数据源连接池(使用druid-spring-boot-starter配置)

一、Druid的简介:

Druid首先是一个数据库连接池。Druid是目前最好的数据库连接池,在功能、性能、扩展性方面,都超过其他数据库连接池,包括DBCP、C3P0、BoneCP、Proxool、JBoss DataSource。Druid已经在阿里巴巴部署了超过600个应用,经过一年多生产环境大规模部署的严苛考验。Druid是阿里巴巴开发的号称为监控而生的数据库连接池!

Spring Boot 2.0 以上默认使用 Hikari 数据源,可以说 Hikari 与 Driud 都是当前 Java Web 上最优秀的数据源,我们来重点介绍 Spring Boot 如何集成 Druid 数据源,如何实现数据库监控。

同时Druid不仅仅是一个数据库连接池,它包括四个部分:
(1) Druid是一个JDBC组件,它包括三个部分:
(2)基于Filter-Chain模式的插件体系。
(3)DruidDataSource 高效可管理的数据库连接池。
(4) SQLParser

所以Druid可以:
1、充当数据库连接池。
2、可以监控数据库访问性能
3、获得SQL执行日志

二、springboot整合druid方式一案例:

=druid依赖这种方式在实际项目中很少用,因为需要我们配置的东西 比较多,比如需要自己配置各种bean。比较麻烦.不建议使用

准备数据库:

本人机器上安装的是mysql8.0.22版本:

我们可以创建一个test数据库,然后在test数据库中创建一个表t_book

这里我使用sqlyog,也可以使用navcat等
在这里插入图片描述

然后点击保存即可。

① 创建maven项目:springboot-data-druid:

在这里插入图片描述

在这里插入图片描述

② 添加druid等依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>springboot-data-druid</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <!--引入druid数据源了连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.21</version>
        </dependency>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>
        <!--mybatis来操作数据库-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>

        <!--springboot-web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.5.0</version>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.18</version>
        </dependency>
        <!--slf4j日志,不导入会报错-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.28</version>
        </dependency>
    </dependencies>
</project>

③ 编写application.yml:

yml中切换数据源;之前已经说过 Spring Boot 2.0 以上默认使用 com.zaxxer.hikari.HikariDataSource 数据源,但可以 通过 spring.datasource.type 指定数据源。

spring:
  #druid数据源连接池,和pom配合使用,5项
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource  #明确指明使用druid

配置监控信息的yml:

spring:
  #druid数据源连接池,和pom配合使用,5项
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource  #明确指明使用druid

    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    #   配置监控统计拦截的filters,stat:监控统计、Log4j:日志记录、wall:防御sql注入
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

④ 写主启动类:

com.example.SpringbootDruidMain:

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

⑤ 配置Druid的监控功能等的bean:

然后创建一个配置类:
com.example.config.DruidConfig

package com.example.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
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 javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource  druidDataSource() {
        return new DruidDataSource();
    }

    //配置后台Druid监控功能
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");

        //后台需要登录
        HashMap<String,String> initParameters = new HashMap<>();

        //增加配置
        initParameters.put("loginUsername", "admin");
        initParameters.put("loginPassword","123456");

        //允许谁可以访问
        initParameters.put("allow", "");  //允许所有访问

        //禁止谁能访问
        initParameters.put("druid", "192.168.11.123");

        //设置初始化参数
        bean.setInitParameters(initParameters);

        return bean;
    }
    //配置一个web监控的filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());

        Map<String,String> initParams = new HashMap<>();

        //不进行统计
        initParams.put("exclusions","*.js,*.css,/druid/*"); //排除静态资源和请求

        bean.setInitParameters(initParams);

        bean.setUrlPatterns(Arrays.asList("/*"));  //拦截所有请求

        return  bean;
    }
}

⑥ 业务类:

6.1实体类domain.Book:

package com.example.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Book{
    private int id;
    private String name;
    private String author;
    public Book(String name,String author){
        this.name = name;
        this.author = author;
    }

}

测试访问:

访问:http://127.0.0.1:8080/druid/login.html输入admin/123456进行登录

想要操作数据库的整体案例,做好结合druid和mybatis来操作。后续更新。

三、springboot整合druid方式二案例:

这种方式不需要配置config包下的各种bean了,简单了很多,推荐使用

导入druid-spring-boot-starter等依赖:

导入druid和springboot的整合依赖:Druid Spring Boot Starter:
Druid Spring Boot Starter 用于帮助你在Spring Boot项目中轻松集成Druid数据库连接池和监控。

<dependencies>
        <!--引入druid数据源了连接池-->
        </dependency>-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.17</version>
        </dependency>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>
        <!--mybatis-spring-boot-starter-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        <!--springboot-web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.5.0</version>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.18</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>
	<!-- 打包为可执行jar -->
	<build>
		<plugins>
			<plugin>
				<groupId> org.springframework.boot </groupId>
				<artifactId> spring-boot-maven-plugin </artifactId>
			</plugin>
		</plugins>
	</build>

application.properties:

#Druid Spring Boot Starter 配置属性的名称完全遵照 Druid依赖,你可以通过 Spring Boot 配置文件来配置Druid数据库连接池和监控,如果没有配置则使用默认值。
#JDBC 配置
#spring.datasource.druid.url= jdbc:mysql://localhost:3306/shiro?useUnicode=true&characterEncoding=utf-8&useSSL=false
#spring.datasource.druid.username= root
#spring.datasource.druid.password= 123456
#spring.datasource.druid.driver-class-name= com.mysql.jdbc.Driver

#################druid-spring-boot-starter等同以上配置##########################
spring.datasource.url= jdbc:mysql://localhost:3306/shiro?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username= root
spring.datasource.password= 123456
spring.datasource.driver-class-name= com.mysql.jdbc.Driver

yml:

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
    password: root
    username: root
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource  #当前数据源操作类型
    druid:
      aop-patterns: com.fan.admin.*  #监控springbean
      filters: stat,wall  #底层开启功能,stat(sql监控),wall(防火墙)

      stat-view-servlet: #配置监控页功能
        enabled: true
        login-username: admin
        login-password: 123
        reset-enable: false

      web-stat-filter: #监控web
        enabled: true
        url-pattern: /*
        exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'

      filter: #对上面filter里面的stat的详细配置,防火墙的配置
        stat:
          slow-sql-millis: 1000
          log-slow-sql: true
          enabled: true
        wall:
          enabled: true
          config:
            drop-table-allow: false  #不允许删表


2.监控配置的properties:(这里可以设置监控页面的登录密码等)

#配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.druid.filters= stat,wall


#######监控配置
# WebStatFilter配置,说明请参考Druid Wiki,配置_配置WebStatFilter
spring.datasource.druid.web-stat-filter.enabled=true
spring.datasource.druid.web-stat-filter.url-pattern=/*
spring.datasource.druid.web-stat-filter.exclusions=/druid/*,*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico
spring.datasource.druid.web-stat-filter.session-stat-enable=true
spring.datasource.druid.web-stat-filter.session-stat-max-count=10
spring.datasource.druid.web-stat-filter.principal-session-name=session_name
spring.datasource.druid.web-stat-filter.principal-cookie-name=cookie_name
spring.datasource.druid.web-stat-filter.profile-enable=
# StatViewServlet配置,说明请参考Druid Wiki,配置_StatViewServlet配置默认false
spring.datasource.druid.stat-view-servlet.enabled=true
# 配置DruidStatViewServlet
spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*
#  禁用HTML页面上的“Reset All”功能
spring.datasource.druid.stat-view-servlet.reset-enable=false
spring.datasource.druid.stat-view-servlet.login-username=admin #监控页面登录的用户名
spring.datasource.druid.stat-view-servlet.login-password=123456 #监控页面登录的密码
#IP白名单(没有配置或者为空,则允许所有访问)
spring.datasource.druid.stat-view-servlet.allow=127.0.0.1,192.168.0.119
#IP黑名单 (存在共同时,deny优先于allow)
spring.datasource.druid.stat-view-servlet.deny=
#Spring监控配置,说明请参考Druid Github Wiki,配置_Druid和Spring关联监控配置
spring.datasource.druid.aop-patterns= com.lcf.service.*

到这里就配置完了,没错配置完了,就是这么骚,接下来运行项目检查下:
这里重点说明:druid-spring-boot-starter已经默认配置好了一些监控等bean这些属性(spring.dataSource==spring.datasource.druid),你只需添加依赖即可,一切操作和以前一样处理

登录监控页面:
http://localhost:8080/druid/
账号:admin 密码123456(properties文件中你自己设置的)

代码演示,数据层使用mybatis,后续更新。

  • 4
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值