SpringBoot(七):集成DataSource 与 Druid监控配置

时间:2024-03-22 11:06:38

绑定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配置内容为:

 <?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.dx</groupId>
<artifactId>springboot-helloword</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>springboot-helloword</name>
<description>Demo project for Spring Boot</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--完成get set toString注册 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--springboot 热部署工具-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--druid 依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
<!--MySQL Driver驱动包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Spring Boot的JPA依赖包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

自定义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=
spring.datasource.druid.min-idle=
spring.datasource.druid.max-active=
# 配置获取连接等待超时的时间
spring.datasource.druid.max-wait=
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.druid.time-between-eviction-runs-millis=
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.druid.min-evictable-idle-time-millis=
spring.datasource.druid.validation-query=SELECT 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=
# 配置监控统计拦截的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=
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.druid.connect-properties.=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=
# 合并多个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监控配置