SpringBoot:集成DataSource 与 Druid监控配置

Posted yy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot:集成DataSource 与 Druid监控配置相关的知识,希望对你有一定的参考价值。

绑定DataSource:Spring Boot默认的数据源是:org.apache.tomcat.jdbc.pool.DataSource,Druid是Java语言中最好的数据库连接池,并且能够提供强大的监控和扩展功能,而且datasource是一般项目都需要使用的功能。因此,这里将学习如何使用springboot与druid集成datasource。

springboot2.0.1+alibaba druid组件导入maven:

1)导入alibaba druid组件:

        <!--druid 依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>

备注:具体请查看官网提供的使用介绍:https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter

2)导入mysql驱动包:

        <!--MySQL Driver驱动包-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

3)导入springboot jpa集成组件:

        <!-- Spring Boot的JPA依赖包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

此时,pom.xml配置内容为:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 4     <modelVersion>4.0.0</modelVersion>
 5 
 6     <groupId>com.dx</groupId>
 7     <artifactId>springboot-helloword</artifactId>
 8     <version>0.0.1-SNAPSHOT</version>
 9     <packaging>jar</packaging>
10 
11     <name>springboot-helloword</name>
12     <description>Demo project for Spring Boot</description>
13 
14     <parent>
15         <groupId>org.springframework.boot</groupId>
16         <artifactId>spring-boot-starter-parent</artifactId>
17         <version>2.0.1.RELEASE</version>
18         <relativePath/> <!-- lookup parent from repository -->
19     </parent>
20 
21     <properties>
22         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
23         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
24         <java.version>1.8</java.version>
25     </properties>
26 
27     <dependencies>
28         <dependency>
29             <groupId>org.springframework.boot</groupId>
30             <artifactId>spring-boot-starter-web</artifactId>
31         </dependency>
32         <!--完成get set toString注册 -->
33         <dependency>
34             <groupId>org.projectlombok</groupId>
35             <artifactId>lombok</artifactId>
36         </dependency>
37         <!--springboot 热部署工具-->
38         <dependency>
39             <groupId>org.springframework.boot</groupId>
40             <artifactId>spring-boot-devtools</artifactId>
41             <optional>true</optional>
42         </dependency>
43         <dependency>
44             <groupId>org.springframework.boot</groupId>
45             <artifactId>spring-boot-starter-test</artifactId>
46             <scope>test</scope>
47         </dependency>
48         <dependency>
49             <groupId>org.springframework.boot</groupId>
50             <artifactId>spring-boot-starter-thymeleaf</artifactId>
51         </dependency>
52         <!--druid 依赖-->
53         <dependency>
54             <groupId>com.alibaba</groupId>
55             <artifactId>druid-spring-boot-starter</artifactId>
56             <version>1.1.9</version>
57         </dependency>
58         <!--MySQL Driver驱动包-->
59         <dependency>
60             <groupId>mysql</groupId>
61             <artifactId>mysql-connector-java</artifactId>
62             <scope>runtime</scope>
63         </dependency>
64         <!-- Spring Boot的JPA依赖包-->
65         <dependency>
66             <groupId>org.springframework.boot</groupId>
67             <artifactId>spring-boot-starter-data-jpa</artifactId>
68         </dependency>
69     </dependencies>
70 
71     <build>
72         <plugins>
73             <plugin>
74                 <groupId>org.springframework.boot</groupId>
75                 <artifactId>spring-boot-maven-plugin</artifactId>
76             </plugin>
77         </plugins>
78     </build>
79 
80 
81 </project>
View Code

自定义datasource配置项加载:

1)在src/resources/application.properties中添加以下配置信息:

# 自定义 数据库配置信息
db.username=root
db.password=root
db.url=jdbc:mysql://localhost:3306/springboot_helloword
db.driver-class-name=com.mysql.jdbc.Driver

2)修改项目的启动入口,添加DataSource的bean注入,及标注自定义参数配置注入:

package com.dx.controller;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;

@SpringBootApplication
public class SpringbootHellowordApplication {

    @Bean
    @ConfigurationProperties(prefix = "db")
    public DataSource dateSource() {
        DruidDataSource dataSource = new DruidDataSource();
        return dataSource;
    }

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

这里的dateSource() 启到的作用就是注入datasourcebean,同时加载自定义配置项的作用。

3)添加测试controller服务HelloWordController.java类:

package com.dx.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

@Controller
public class HelloWordController {
    @Autowired
    private DataSource dataSource;

    @RequestMapping("/index")
    @ResponseBody
    public String index() throws SQLException {
        System.out.println(dataSource.getConnection());
        System.out.println(dataSource);
        return "hello spring boot";
    }
}

4)测试,在浏览器中访问http://localhost:8888/index,查看控制台打印信息:

com.mysql.jdbc.JDBC4Connection@7120165d
{
    CreateTime:"2018-04-09 20:41:41",
    ActiveCount:1,
    PoolingCount:0,
    CreateCount:1,
    DestroyCount:0,
    CloseCount:4,
    ConnectCount:5,
    Connections:[
    ]
}

使用springboot集成的datasource配置项:

1)修改datasource参数配置,使用系统集成参数配置项:

## 自定义 数据库配置信息
#db.username=root
#db.password=root
#db.url=jdbc:mysql://localhost:3306/springboot_helloword
#db.driver-class-name=com.mysql.jdbc.Driver
#druid datasouce database settings begin
spring.datasource.druid.db-type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.driverClassName=com.mysql.jdbc.Driver
spring.datasource.druid.url=jdbc:mysql://localhost:3306/springboot_helloword?allowMultiQueries=true&autoReconnect=true&characterEncoding=utf-8
spring.datasource.druid.username=root
spring.datasource.druid.password=root
# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
spring.datasource.druid.initial-size=5
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-active=20
# 配置获取连接等待超时的时间
spring.datasource.druid.max-wait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.druid.time-between-eviction-runs-millis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.druid.min-evictable-idle-time-millis=300000
spring.datasource.druid.validation-query=SELECT 1 FROM DUAL
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.test-on-return=false
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.druid.pool-prepared-statements=true
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,\'wall\'用于防火墙
spring.datasource.druid.filter.commons-log.connection-logger-name=stat,wall,log4j
spring.datasource.druid.filter.stat.log-slow-sql=true
spring.datasource.druid.filter.stat.slow-sql-millis=2000
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.druid.connect-properties.=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
spring.datasource.druid.use-global-data-source-stat=true

2)在springboot服务启动类不用注入其他bean和加载参数配置:

package com.dx.controller;

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

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

3)测试服务类HelloWordController.java与上边一样即可。

4)测试,在浏览器中访问http://localhost:8888/index,查看控制台打印信息:

com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@3e6c29a1
{
    CreateTime:"2018-04-09 21:15:51",
    ActiveCount:1,
    PoolingCount:4,
    CreateCount:5,
    DestroyCount:0,
    CloseCount:4,
    ConnectCount:5,
    Connections:[
        {ID:1407373927, ConnectTime:"2018-04-09 21:15:51", UseCount:0, LastActiveTime:"2018-04-09 21:15:51"},
        {ID:485935020, ConnectTime:"2018-04-09 21:15:51", UseCount:0, LastActiveTime:"2018-04-09 21:15:51"},
        {ID:1400896839, ConnectTime:"2018-04-09 21:15:51", UseCount:0, LastActiveTime:"2018-04-09 21:15:51"},
        {ID:209844136, ConnectTime:"2018-04-09 21:15:51", UseCount:0, LastActiveTime:"2018-04-09 21:15:51"}
    ]
}

[
    {ID:1407373927,poolStatements:[]},
    {ID:485935020,poolStatements:[]},
    {ID:1400896839,poolStatements:[]},
    {ID:209844136,poolStatements:[]}
]

 配置监控统计功能:

1)配置Servlet(监控视图配置):

如下是在SpringBoot项目中基于注解的配置,如果是web.xml配置,按规则配置即可。

package com.base.servlet;

import com.alibaba.druid.support.http.StatViewServlet;

import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;

/**
 * druid数据源状态监控.
 * */
@WebServlet(urlPatterns="/druid/*",
        initParams={
                @WebInitParam(name="allow",value="192.168.1.72,127.0.0.1"),// IP白名单(没有配置或者为空,则允许所有访问)
                @WebInitParam(name="deny",value="192.168.1.73"),// IP黑名单 (存在共同时,deny优先于allow)
                @WebInitParam(name="loginUsername",value="admin"),// 用户名
                @WebInitParam(name="loginPassword",value="123456"),// 密码
                @WebInitParam(name="resetEnable",value="false")// 禁用html页面上的“Reset All”功能
        }
)
public class DruidStatViewServlet extends StatViewServlet {
    private static final long serialVersionUID = 1L;

}

2)过滤不需要监控的后缀:

package com.base.servlet;

import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;

import com.alibaba.druid.support.http.WebStatFilter;

/**
 * druid过滤器.
 */
@WebFilter(filterName = "druidWebStatFilter", urlPatterns = "/*",
        initParams = {
                @WebInitParam(name = "exclusions", value = "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")//忽略资源
        }
)
public class DruidStatFilter extends WebStatFilter {

}

3)测试配置是否成功。

访问网址:http://localhost:8888/druid/index.html

 

以上是关于SpringBoot:集成DataSource 与 Druid监控配置的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot集成前端模版(thymeleaf)

SpringBoot集成多数据源

idea 中 springBoot 集成 h2 轻量级内存数据库

SpringBoot 集成sharding-jdbc 提示:Failed to configure a DataSource: ‘url‘ attribute is not specified ***

springboot集成starrocks以及采用flink实现mysql与starrocks亚秒级同步

spring boot集成mybatis+事务控制