【WEEK12】 【DAY2】整合Druid数据源【中文版】

2024.5.14 Tuesday

目录

  • 12.整合Druid数据源
    • 12.1.Druid简介
    • 12.2.配置数据源
      • 12.2.1.添加Druid数据源依赖
      • 12.2.2.切换数据源
      • 12.2.3.运行Springboot04DataApplicationTests.java
      • 12.2.4.尝试使用Druid数据源的专有配置
      • 12.2.5.导入Log4j 的依赖
      • 12.2.6.新建config文件夹
      • 12.2.7.修改测试类并运行检查配置参数是否生效
    • 12.3.配置Druid数据源监控
      • 12.3.1.修改DruidConfig.java
      • 12.3.2.重启并访问http://localhost:8080/druid
      • 12.3.3.配置Druid web监控filter过滤器

12.整合Druid数据源

12.1.Druid简介

Java程序很大一部分要操作数据库,为了提高性能操作数据库的时候,又不得不使用数据库连接池。
Druid 是阿里巴巴开源平台上一个数据库连接池实现,结合了 C3P0、DBCP 等 DB 池的优点,同时加入了日志监控。
Druid 可以很好的监控 DB 池连接和 SQL 的执行情况,天生就是针对监控而生的 DB 连接池。
Druid已经在阿里巴巴部署了超过600个应用,经过一年多生产环境大规模部署的严苛考验。
Spring Boot 2.0 以上默认使用 Hikari 数据源,可以说 Hikari 与 Driud 都是当前 Java Web 上最优秀的数据源,我们来重点介绍 Spring Boot 如何集成 Druid 数据源,如何实现数据库监控。
Github地址:https://github.com/alibaba/druid/
com.alibaba.druid.pool.DruidDataSource 基本配置参数如下:
在这里插入图片描述
在这里插入图片描述

12.2.配置数据源

12.2.1.添加Druid数据源依赖

https://mvnrepository.com/artifact/com.alibaba/druid/1.1.21
在这里插入图片描述
修改pom.xml,在dependencies中添加这段依赖

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.13</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>springboot-04-data</artifactId><version>0.0.1-SNAPSHOT</version><name>springboot-04-data</name><description>springboot-04-data</description><properties><java.version>8</java.version></properties><dependencies><!--Druid--><!-- https://mvnrepository.com/artifact/com.alibaba/druid --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.21</version></dependency><!--JDBC--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--MySQL--><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

重启maven进行下载,可以点开源码查看
在这里插入图片描述

12.2.2.切换数据源

修改application.yaml

spring:datasource:username: rootpassword: 123456#假如时区报错,就增加一个时区的配置,和其他配置用&连接,如:serverTimezone=UTCurl: jdbc:mysql://localhost:3306/p37jdbc?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8driver-class-name: com.mysql.cj.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSource

12.2.3.运行Springboot04DataApplicationTests.java

此时默认数据源已经改变,但是数据库底层仍然是JDBC:
在这里插入图片描述

12.2.4.尝试使用Druid数据源的专有配置

修改修改application.yaml

spring:datasource:username: rootpassword: 123456#假如时区报错,就增加一个时区的配置,和其他配置用&连接,如:serverTimezone=UTCurl: jdbc:mysql://localhost:3306/p37jdbc?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8driver-class-name: com.mysql.cj.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSource#Spring Boot 默认是不注入这些属性值的,需要自己绑定#druid 数据源专有配置initialSize: 5minIdle: 5maxActive: 20maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true#配置监控统计拦截的filters,stat:监控统计; log4j:日志记录; wall:防御sql注入#如果允许时报错  java.lang.ClassNotFoundException: org.apache.log4j.Priority#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4jfilters: stat,wall,log4jmaxPoolPreparedStatementPerConnectionSize: 20useGlobalDataSourceStat: trueconnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

12.2.5.导入Log4j 的依赖

pom.xml中添加依赖

<!--log4j-->
<dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version>
</dependency>

12.2.6.新建config文件夹

现在需要程序员自己为 DruidDataSource 绑定全局配置文件中的参数,再添加到容器中,而不再使用 Spring Boot 的自动生成了;我们需要 自己添加 DruidDataSource 组件到容器中,并绑定属性;
新建DruidConfig.java
在这里插入图片描述

package com.P31.config;import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import javax.sql.DataSource;@Configuration
public class DruidConfig {/*将自定义的 Druid数据源添加到容器中,不再让 Spring Boot 自动创建绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效@ConfigurationProperties(prefix = "spring.datasource"):作用就是将 全局配置文件中前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中*/@ConfigurationProperties(prefix = "spring.datasource")  //绑定@Beanpublic DataSource druidDataSource(){return new DruidDataSource();}
}

12.2.7.修改测试类并运行检查配置参数是否生效

Springboot04DataApplicationTests.java

package com.P31;import com.alibaba.druid.pool.DruidDataSource;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;@SpringBootTest
class Springboot04DataApplicationTests {@AutowiredDataSource dataSource;@Testvoid contextLoads() throws SQLException {//查看默认的数据源System.out.println(dataSource.getClass());//获取数据库连接Connection connection = dataSource.getConnection();System.out.println(connection);DruidDataSource druidDataSource = (DruidDataSource) dataSource;System.out.println("druidDataSource 数据源最大连接数:" + druidDataSource.getMaxActive());System.out.println("druidDataSource 数据源初始化连接数:" + druidDataSource.getInitialSize());//关闭connection.close();}}

在这里插入图片描述

12.3.配置Druid数据源监控

Druid数据源具有监控的功能,而且提供了一个web页面便于查看。

12.3.1.修改DruidConfig.java

package com.P31.config;import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import org.springframework.boot.context.properties.ConfigurationProperties;
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.HashMap;@Configuration
public class DruidConfig {/*将自定义的 Druid数据源添加到容器中,不再让 Spring Boot 自动创建绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效@ConfigurationProperties(prefix = "spring.datasource"):作用就是将 全局配置文件中前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中*/@ConfigurationProperties(prefix = "spring.datasource")  //绑定@Beanpublic DataSource druidDataSource(){return new DruidDataSource();}//后台监控//配置 Druid 监控管理后台的Servlet;//因为SpringBoot内置了Servlet容器,所以没有web.xml文件,所以使用Spring Boot的注册Servlet方式(ServletRegistrationBean)@Beanpublic ServletRegistrationBean statViewServlet(){ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");//后台需要有人登录,账号密码配置//点开setInitParameters查看源码,可以看到他需要的参数:public void setInitParameters(Map<String, String> initParameters)HashMap<String,String> initParameters = new HashMap<>();//这些参数可以在 com.alibaba.druid.support.http.StatViewServlet的父类 com.alibaba.druid.support.http.ResourceServlet 中找到//增加配置//loginUsername loginPassword是固定参数initParameters.put("loginUsername","admin");    //后台管理界面的登录账号initParameters.put("loginPassword","123456");   //后台管理界面的登录密码//允许可以访问的用户initParameters.put("allow",""); //为空则所有人都可以访问//initParams.put("allow", "localhost"):表示只有本机可以访问//initParams.put("allow", ""):为空或者为null时,表示允许所有访//禁止访问的用户//deny:Druid 后台拒绝谁访问//initParams.put("kuangshen", "192.168.1.20");表示禁止此ip访问bean.setInitParameters(initParameters);   //设置初始化参数return bean;}
}

12.3.2.重启并访问http://localhost:8080/druid

将自动跳转到http://localhost:8080/druid/login.html
在这里插入图片描述
登录参数错误:
在这里插入图片描述
成功登录:
在这里插入图片描述
跳转到:
在这里插入图片描述
运行http://localhost:8080/userList,点击导航栏中的“SQL监控”可见:
在这里插入图片描述

也可查看SQL防火墙:
在这里插入图片描述

12.3.3.配置Druid web监控filter过滤器

package com.P31.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 {/*将自定义的 Druid数据源添加到容器中,不再让 Spring Boot 自动创建绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效@ConfigurationProperties(prefix = "spring.datasource"):作用就是将 全局配置文件中前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中*/@ConfigurationProperties(prefix = "spring.datasource")  //绑定@Beanpublic DataSource druidDataSource(){return new DruidDataSource();}//后台监控//配置 Druid 监控管理后台的Servlet;//因为SpringBoot内置了Servlet容器,所以没有web.xml文件,所以使用Spring Boot的注册Servlet方式(ServletRegistrationBean)@Beanpublic ServletRegistrationBean statViewServlet(){ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");//后台需要有人登录,账号密码配置//点开setInitParameters查看源码,可以看到他需要的参数:public void setInitParameters(Map<String, String> initParameters)HashMap<String,String> initParameters = new HashMap<>();//这些参数可以在 com.alibaba.druid.support.http.StatViewServlet的父类 com.alibaba.druid.support.http.ResourceServlet 中找到//增加配置//loginUsername loginPassword是固定参数initParameters.put("loginUsername","admin");    //后台管理界面的登录账号initParameters.put("loginPassword","123456");   //后台管理界面的登录密码//允许可以访问的用户initParameters.put("allow",""); //为空则所有人都可以访问//initParams.put("allow", "localhost"):表示只有本机可以访问//initParams.put("allow", ""):为空或者为null时,表示允许所有访//禁止访问的用户//deny:Druid 后台拒绝谁访问//initParams.put("kuangshen", "192.168.1.20");表示禁止此ip访问bean.setInitParameters(initParameters);   //设置初始化参数return bean;}//filter//配置 Druid 监控 之  web 监控的 filter//WebStatFilter:用于配置Web和Druid数据源之间的管理关联监控统计@Beanpublic FilterRegistrationBean webStatFilter(){FilterRegistrationBean bean = new FilterRegistrationBean();bean.setFilter(new WebStatFilter());//exclusions:设置哪些请求被过滤(排除)->不进行统计Map<String,String> initParameters = new HashMap<>();initParameters.put("exclusions","*.js,*.css,/druid/*,/jdbc/*");bean.setInitParameters(initParameters);//"/*" 表示过滤所有请求bean.setUrlPatterns(Arrays.asList("/*"));return bean;}
}

按需配置即可。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/12601.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

短视频人设定位有哪些:四川京之华锦信息技术公司

短视频人设定位有哪些&#xff1a;打造独特魅力的关键 随着短视频平台的兴起&#xff0c;越来越多的内容创作者开始涌现&#xff0c;他们凭借各自独特的魅力在网络世界中崭露头角。而在这其中&#xff0c;一个成功的短视频账号背后&#xff0c;往往有一个清晰、鲜明的人设定位…

安卓APP+TCP+服务器端

1、在.xml文件中添加权限 <uses-permission android:name"android.permission.ACCESS_WIFI_STATE"/><uses-permission android:name"android.permission.INTERNET"/>2、修改显示界面 <?xml version"1.0" encoding"utf-8&…

短剧私域-快速引流变现

短剧的爆火&#xff0c;衍生出了很多周边项目。 比如免费看剧App&#xff0c;短剧搜索机器人&#xff0c;短剧付费圈子等等。 这些项目的本质&#xff0c;就是借助短剧的热度&#xff0c;把流量引到自己的鱼塘进行变现。 短剧机器人大家都知道&#xff0c;目前最火的一种玩法…

【大数据面试题】27 讲下Doris的物化视图

一步一个脚印&#xff0c;一天一道面试题。 物化视图概念 物化视图&#xff0c;顾名思义&#xff0c;是将一个查询的结果预先计算并存储为物理表的形式。这意味着&#xff0c;原本需要在运行时动态执行的复杂查询&#xff0c;现在变成了直接从已经计算好的结果表中读取数据&a…

vue一个简易时钟

<template><div class"">时间{{ time }}<div class"base1"><div class"move-to-center line"></div><div class"move-to-center line line2"></div><div class"move-to-center lin…

单链表经典算法OJ题--牛客(环形链表的约瑟夫问题

链接&#xff1a;环形链表的约瑟夫问题_牛客题霸_牛客网【点击即可跳转】 著名的Josephus问题 据说著名犹太历史学家 Josephus有过以下的故事&#xff1a; 在罗马人占领乔塔帕特后&#xff0c;39 个犹太⼈与 Josephus及他的朋友躲到⼀个洞中&#xff0c;39个犹太⼈决定宁愿死也…

部标JT809开源(go版本)

GitHub - Yordroid/jt809_server: 部标809下级平台&#xff0c;支持2011&#xff0c;2013,2019 欢迎大家给波星

网络接口类型

第二天&#xff08;网络、接口类型&#xff09; 网络类型&#xff1a; 1、点到点&#xff1a;在一个网段内只能存在&#xff0c;两个物理节点 MA --- 多路访问 -- 在一个网段内物理节点的数量不限制 MA --- BMA NBMA 2、BMA --- 广播型多路访问 3、NBMA --- 非广播型多路…

智能鱼缸-设计说明书

设计摘要&#xff1a; 本论文以STC89C52单片机为核心控制器&#xff0c;构建了一套智能鱼缸系统。该系统由中控部分、输入部分和输出部分组成。中控部分采用STC89C52单片机&#xff0c;负责获取输入部分数据并进行处理&#xff0c;控制输出部分。输入部分包括TDS水质水温检测模…

MySQL:查询一个由逗号分隔的字符串数组,并检查其中指定元素是否等于某个值

使用SUBSTRING_INDEX函数 SELECT * FROM TABLE_NAME WHERE SUBSTRING_INDEX(SUBSTRING_INDEX(status, ,, 2), ,, -1) 1SUBSTRING_INDEX()函数 用于提取字符串中的子字符串。函数有三个参数&#xff1a; 第一个参数是源字符串&#xff0c;这是您要从中提取子字符串的字符串。…

Axure RP移动端交互元件库/交互原型模板

作品类型&#xff1a;元件库/原型模板 更新日期&#xff1a;2023-12-04 当前版本&#xff1a;V1.3 适用范围&#xff1a;App应用/小程序 Axure版本&#xff1a;Axure 9.0均可打开 文件大小&#xff1a;36.7M 历时两个月制作并整理了手机移动端常用的75种组件、90个常用界面模板…

Hadoop复习(上)

目录 一 绪论 1 大数据5v特点 --1.6 2 Google三驾马车 GFS MapReduce BigTable --1.18 3 Hadoop的特点 --1.23 4 Hadoop生态系统 (教材p6) 6 NoSQL有哪些 二 HDFS架构 1 三大基本组件 --2.1.2 2 HDFS特性和局限性(教材p38) --2.1.4-5 3 HDFS block 4 HDFS守护进程 …

设计模式六大原则之 接口分离原则

文章目录 概念比较代码示例优势 小结 概念 要为各个类建立它们需要的专用接口&#xff0c;而不要试图去建立一个很庞大的接口供所有依赖它的类去调用。 比较 概念有了&#xff0c;再来看看比较下吧&#xff0c;和单一职责比较比较。 接口隔离原则和单一职责都是为了提高类的…

pyenv 之 python 多版本管理(win11)

1. 背景 常常会用到Python的多个版本&#xff0c;因此可以使用Pyenv来对Python版本进行管理。 2. win11下载 pyenv 在终端执行下载语句&#xff1a; pip install pyenv-win --target D:\software\pyenv 其中 D:\software\pyenv 为你想要下载到的文件目录&#xff0c;建议在 …

数字功放-改善液晶显示屏音频性能,重塑音频体验

随着液晶电视、液晶显示器以及等离子电视屏幕的尺寸不断增大&#xff0c;音频性能要求相应提高&#xff1b;数字功放芯片作为音频解决方案&#xff1b;不仅为音频设备带来更高的效率和更低的功耗&#xff0c;同时在显示屏上进一步提高了平板显示器的音质&#xff0c;使之具有了…

常用正则 JS 持续更新

应用版本号正则验证 正则判断版本号&#xff08;如&#xff1a;1.2.3 或 1.2.3.4&#xff09;&#xff0c;不允许出现 0.x.x&#xff1b;01.x.x; x.0x.x; x.00.x&#xff1b; x.x.00; x.x.0x/ ^ ([ 1-9 ] \d | [ 1-9 ])( . ([ 1-9 ] \d | \d )) {2,3} $ /0-10 保留一位小数的数…

Git系列:git add 被忽视的操作技巧

&#x1f49d;&#x1f49d;&#x1f49d;欢迎莅临我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐:「stormsha的主页」…

[Linux]一篇文章带你全面理解信号

文章目录 初识信号一、什么是信号二、为什么要有信号 看见信号一、先见一下Linux中的信号&#xff1a;二、如何产生信号三、自定义信号的处理行为&#xff08;自定义捕捉&#xff09; 了解信号一、信号的保存二、block、pending表使用代码查看三、一些倔强的&#xff0c;无法被…

排列三利用大数据预测

排列三是一种基于随机数字生成的游戏&#xff0c;因此从纯数学的角度来看&#xff0c;利用大数据进行预测并不能确保中奖。然而&#xff0c;大数据和数据分析确实可以为我们提供一些参考和指导&#xff0c;帮助我们在投注时做出更明智的决策。 首先&#xff0c;大数据可以帮助…

【Redis】Redis键值存储

大家好&#xff0c;我是白晨&#xff0c;一个不是很能熬夜&#xff0c;但是也想日更的人。如果喜欢这篇文章&#xff0c;点个赞&#x1f44d;&#xff0c;关注一下&#x1f440;白晨吧&#xff01;你的支持就是我最大的动力&#xff01;&#x1f4aa;&#x1f4aa;&#x1f4aa…