SpringBoot【1】集成 Druid

SpringBoot 集成 Druid

  • 前言
  • 创建项目
  • 修改 pom.xml 文件
  • 添加配置文件
  • 开发 java 代码
    • 启动类 - DruidApplication
    • 配置文件-properties
      • DruidConfigProperty
      • DruidMonitorProperty
    • 配置文件-config
      • DruidConfig
    • 控制层
      • DruidController
  • 运行
  • 验证
    • Druid 的监控
    • 应用程序

前言

JDK版本:1.8
Maven版本:3.8.1
操作系统:Win10
SpringBoot版本:2.3.12.RELEAS

  • 当前 Springboot 版本选用2.3.12.RELEASE ,关于版本的选择,这里先说明下,后续不在重复说明。
  • 我日常微服务项目技术栈用到 Spring Cloud Alibaba 版本选用的是2.2.8.release,而此版本对应的SpringBoot版本官方建议是 2.3.12.RELEASE ,故Spring Boot系列项目也通用使用 2.2.8.release
  • 在这里插入图片描述

创建项目

  1. File => New => Project
    在这里插入图片描述
  2. 选择:Maven(注意:IDEA工具已经提前配置好了Maven、JDK等)
    在这里插入图片描述
  3. 填写属性,这里主要更改了:NameGroupId,最后点击Finish按钮即可。
    由于junjiu-springboot-druid已经创建完成,这里笔记时,故写成了jj-springboot-druid后续笔记中使用的是junjiu-springboot-druid (只是一个项目名字,问题不大)
    在这里插入图片描述
    项目创建完成之后,如下:

在这里插入图片描述

修改 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><parent><artifactId>spring-boot-starter-parent</artifactId><groupId>org.springframework.boot</groupId><version>2.3.12.RELEASE</version><relativePath /></parent><groupId>com.junjiu.springboot.druid</groupId><artifactId>junjiu-springboot-druid</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><mysql.connector.java.version>8.0.28</mysql.connector.java.version><mybatis.plus.boot.starter.version>3.3.1</mybatis.plus.boot.starter.version><druid.version>1.2.13</druid.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- MySQL驱动依赖. --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>${mysql.connector.java.version}</version></dependency><!-- mybatis-plus 依赖https://baomidou.com/getting-started/--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version> ${mybatis.plus.boot.starter.version} </version></dependency><!-- Druid --><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>${druid.version}</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><!-- lombok 依赖 --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency></dependencies></project>

添加配置文件

resources目录中创建application.yml配置文件
在这里插入图片描述
配置文件内容如下:

# 端口
server:port: 5826spring:application:# 应用名称name: junjiu-springboot-druiddatasource:type: com.alibaba.druid.pool.DruidDataSourcedruid:driver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://192.168.88.54:3306/ideadb?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=falseusername: fid_ideapassword: 123456initial-size: 10max-active: 100min-idle: 10max-wait: 60000pool-prepared-statements: truemax-pool-prepared-statement-per-connection-size: 20time-between-eviction-runs-millis: 60000min-evictable-idle-time-millis: 300000max-evictable-idle-time-millis: 600000validation-query: SELECT 1 FROM DUAL# validation-query-timeout: 5000test-on-borrow: falsetest-on-return: falsetest-while-idle: trueconnection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000#filters: #配置多个英文逗号分隔(统计,sql注入,log4j过滤)filters: stat,wallstat-view-servlet:enabled: trueurl-pattern: /druid/*# 监控页面配置.
jj:druid:monitor:login-username: rootlogin-password: 123456reset-enable: false

开发 java 代码

当前项目的建设,主要两个原因:

  1. 研究MySQL8.x版本中的性能库performance_schema,例如:threadsprocesslist等视图。
  2. SpringBoot 项目集成 Druid,做个笔记。

项目中将可能缺少业务层、持久层等目录结构。

项目代码结构如下:
在这里插入图片描述

启动类 - DruidApplication

package com.junjiu.springboot.druid;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;/*** program: junjiu-springboot-druid* ClassName: DruidApplication* description:** @author: 君九* @create: 2024-05-26 13:13* @version: 1.0**/
@SpringBootApplication
public class DruidApplication {public static void main(String[] args) {SpringApplication.run(DruidApplication.class);}
}

配置文件-properties

DruidConfigProperty

package com.junjiu.springboot.druid.config.properties;import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;/*** program: junjiu-springboot-druid* ClassName: DruidConfigProperty* description:** @author: 君九* @create: 2024-05-26 13:19* @version: 1.0**/
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "spring.datasource.druid")
public class DruidConfigProperty {private String url;private String username;private String password;private String driverClassName;private int initialSize;private int maxActive;private int minIdle;private int maxWait;private boolean poolPreparedStatements;private int maxPoolPreparedStatementPerConnectionSize;private int timeBetweenEvictionRunsMillis;private int minEvictableIdleTimeMillis;private int maxEvictableIdleTimeMillis;private String validationQuery;private boolean testWhileIdle;private boolean testOnBorrow;private boolean testOnReturn;private String filters;private String connectionProperties;}

DruidMonitorProperty

package com.junjiu.springboot.druid.config.properties;import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;/*** program: junjiu-springboot-druid* ClassName: DruidMonitorProperty* description:** @author: 君九* @create: 2024-05-26 13:27* @version: 1.0**/
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "jj.druid.monitor")
public class DruidMonitorProperty {private String loginUsername;private String loginPassword;private String resetEnable;}

配置文件-config

DruidConfig

package com.junjiu.springboot.druid.config;import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.junjiu.springboot.druid.config.properties.DruidConfigProperty;
import com.junjiu.springboot.druid.config.properties.DruidMonitorProperty;
import org.springframework.beans.factory.annotation.Autowired;
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.jdbc.core.JdbcTemplate;/*** program: junjiu-springboot-druid* ClassName: DruidConfig* description: Druid 配置文件** @author: 君九* @create: 2024-05-26 13:16* @version: 1.0**/
@Configuration
public class DruidConfig {@AutowiredDruidConfigProperty druidConfigProperty;@AutowiredDruidMonitorProperty druidMonitorProperty;/*** Druid 连接池配置*/@Beanpublic DruidDataSource dataSource() {DruidDataSource datasource = new DruidDataSource();datasource.setUrl(druidConfigProperty.getUrl());datasource.setUsername(druidConfigProperty.getUsername());datasource.setPassword(druidConfigProperty.getPassword());datasource.setDriverClassName(druidConfigProperty.getDriverClassName());datasource.setInitialSize(druidConfigProperty.getInitialSize());datasource.setMinIdle(druidConfigProperty.getMinIdle());datasource.setMaxActive(druidConfigProperty.getMaxActive());datasource.setMaxWait(druidConfigProperty.getMaxWait());datasource.setTimeBetweenEvictionRunsMillis(druidConfigProperty.getTimeBetweenEvictionRunsMillis());datasource.setMinEvictableIdleTimeMillis(druidConfigProperty.getMinEvictableIdleTimeMillis());datasource.setMaxEvictableIdleTimeMillis(druidConfigProperty.getMaxEvictableIdleTimeMillis());datasource.setValidationQuery(druidConfigProperty.getValidationQuery());datasource.setTestWhileIdle(druidConfigProperty.isTestWhileIdle());datasource.setTestOnBorrow(druidConfigProperty.isTestOnBorrow());datasource.setTestOnReturn(druidConfigProperty.isTestOnReturn());datasource.setPoolPreparedStatements(druidConfigProperty.isPoolPreparedStatements());datasource.setMaxPoolPreparedStatementPerConnectionSize(druidConfigProperty.getMaxPoolPreparedStatementPerConnectionSize());try {datasource.setFilters(druidConfigProperty.getFilters());} catch (Exception ex) {ex.printStackTrace();}datasource.setConnectionProperties(druidConfigProperty.getConnectionProperties());return datasource;}/*** JDBC操作配置*/@Beanpublic JdbcTemplate jdbcTemplate (@Autowired DruidDataSource dataSource){return new JdbcTemplate(dataSource) ;}/*** 配置 Druid 监控界面*/@Beanpublic ServletRegistrationBean statViewServlet(){ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");//设置控制台管理用户servletRegistrationBean.addInitParameter("loginUsername",druidMonitorProperty.getLoginUsername());servletRegistrationBean.addInitParameter("loginPassword",druidMonitorProperty.getLoginPassword());// 是否可以重置数据servletRegistrationBean.addInitParameter("resetEnable",druidMonitorProperty.getResetEnable());return servletRegistrationBean;}@Beanpublic FilterRegistrationBean statFilter(){//创建过滤器FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());//设置过滤器过滤路径filterRegistrationBean.addUrlPatterns("/*");//忽略过滤的形式filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");return filterRegistrationBean;}}

控制层

DruidController

package com.junjiu.springboot.druid.controller;import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;/*** program: junjiu-springboot-druid* ClassName: DruidController* description:** @author: 君九* @create: 2024-05-26 13:32* @version: 1.0**/
@RestController
public class DruidController {@Resourceprivate JdbcTemplate jdbcTemplate;@Autowiredprivate DruidDataSource druidDataSource;/*** 测试 Druid* @return*/@GetMapping("/test")public String testDruid() {String sql = "select version()";String result = jdbcTemplate.queryForObject(sql, String.class);SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");return "Success.".concat(simpleDateFormat.format(new Date())).concat(":").concat(result);}/*** 测试连接池.*  查看 performance_schema.threads 情况.* @param size* @return*/@GetMapping("/mutix/{size}")public String testDruidMutix(@PathVariable("size") Integer size) {for(int k = 0; k < size; k++) {new Thread(() -> {String sql = "select version()";String result = jdbcTemplate.queryForObject(sql, String.class);System.out.println(Thread.currentThread().getName() + ":" + result);}).start();}SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");return "Success.".concat(simpleDateFormat.format(new Date()));}
}

运行

DruidApplication 类中,进行启动。在这里插入图片描述

验证

Druid 的监控

在地址栏访问:http://localhost:5826/druid/ 打开如下页面,输入配置中的账号、密码,即可访问。
在这里插入图片描述
在这里插入图片描述

应用程序

根据控制层代码访问路径,在浏览器地址栏中访问:
http://localhost:5826/test ,如下将会有返回。
在这里插入图片描述

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

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

相关文章

33.perf工具使用

文章目录 基本介绍perf命令使用reference 欢迎访问个人网络日志&#x1f339;&#x1f339;知行空间&#x1f339;&#x1f339; 基本介绍 Perf&#xff08;Performance Counters for Linux&#xff0c;性能计数器子系统&#xff09;是一个Linux性能分析工具&#xff0c;用于分…

分析 Base64 编码和 URL 安全 Base64 编码

前言 在处理数据传输和存储时&#xff0c;Base64 编码是一种非常常见的技术。它可以将二进制数据转换为文本格式&#xff0c;便于在文本环境中传输和处理。Go 语言提供了对标准 Base64 编码和 URL 安全 Base64 编码的支持。本文将通过一个示例代码&#xff0c;来分析这两种编码…

前端开发-添加公用的ts文件,并在Vue文件中引用

一般我们把页面要用的公用函数写在一个ts文件中 通过调用这个ts文件让我们可以在vue文件中使用函数 Eg&#xff1a;我们现在创建一个formRules.ts文件 然后在我们需要调用该函数体的vue文件中 import { required } from "/utils/formRules";有可能语法一开始会提示…

Phobos勒索病毒:最新变种phobos袭击了您的计算机?

一、导言 在数字化浪潮中&#xff0c;网络安全问题日益凸显&#xff0c;而.Phobos勒索病毒无疑是其中的隐形杀手。它潜伏在网络的每一个角落&#xff0c;等待着合适的时机对目标发动致命一击。本文将深入探讨.Phobos勒索病毒的新特点、传播途径&#xff0c;并提出一系列创新的…

C++面试题记录(网络)

TCP与UDP区别 1. TCP面向连接&#xff0c;UDP无连接&#xff0c;所以UDP数据传输效率更高 2.UDP可以支持一对一、一对多、多对一、多对多通信&#xff0c;TCP只能一对一 3. TCP需要在端系统维护连接状态&#xff0c;包括缓存&#xff0c;序号&#xff0c;确认号&#xff0c;…

防火墙——域网络、专用网络、公用网络

在防火墙设置中&#xff0c;域网络、专用网络和公用网络是指计算机连接到网络时所处的不同环境。每种环境都有不同的安全级别和配置。 1、域网络&#xff08;宽松&#xff09; 域网络是指计算机加入了一个Windows域&#xff08;Domain&#xff09;环境&#xff0c;这通常在企业…

程序员的那些经典段子

哈喽&#xff0c;大家好&#xff0c;我是明智&#xff5e; 本周咱们已经解决了在面试中经常碰到的OOM问题&#xff1a; 《美团一面&#xff0c;发生OOM了&#xff0c;程序还能继续运行吗&#xff1f;》 《美团一面&#xff1a;碰到过OOM吗&#xff1f;你是怎么处理的&#xff1…

白嫖的在线工具类宝藏网站清单,快点击进来收藏一波

简单整理了一下自己日常经常使用的10个免费工具网站&#xff0c;建议点赞关注收藏&#xff0c;快点分享给小伙伴们&#xff01; 1.奶牛快传:用户体验更好的网盘工具。 https://cowtransfer.com/ 今年开始使用的一款网盘工具&#xff0c;和百度网盘类似,叫奶牛快传&#xff0c;如…

【设计模式】——装饰模式(包装器模式)

&#x1f4bb;博主现有专栏&#xff1a; C51单片机&#xff08;STC89C516&#xff09;&#xff0c;c语言&#xff0c;c&#xff0c;离散数学&#xff0c;算法设计与分析&#xff0c;数据结构&#xff0c;Python&#xff0c;Java基础&#xff0c;MySQL&#xff0c;linux&#xf…

数据结构--二叉搜索树

目录 二叉搜索树的概念 二叉树的实现 结点类 函数接口总览 实现二叉树 二叉搜索树的应用 K模型 KV模型 二叉搜索树的性能分析 二叉搜索树的概念 二叉搜索树&#xff08;Binary Search Tree&#xff0c;简称BST&#xff09;是一种特殊的二叉树&#xff0c;其具有以下几…

数据库(6)——数据类型

SQL标准常用的数据类型有&#xff1a; 数据类型含义CHAR(n),CHARACTER(n)长度为n的定长字符串VARCHAR&#xff08;n&#xff09;最大长度为n的变长字符串CLOB字符串大对象BLOB二进制大对象SMALLINT2字节 短整数INT , INTEGER4字节 整数BIGINT8字节 大整数FLOAT(n)精度为n的浮点…

6818 android 修改开机 logo, 编译脚本分析

问题&#xff1a; 客户需要去掉 android5.1 的开机logo. 说明&#xff1a; 对于Android5.1 来说&#xff0c;uboot 与kernel 的logo 是一个。 过程&#xff1a; 其实对于开机logo 的修改很简单&#xff0c;直接参考厂家手册就可以了。 这是 android4.4 的开机logo 的修改&…

设计一个代办功能模块

目录 1. 需求分析2. 数据库设计用户表&#xff08;Users Table&#xff09;代办任务表&#xff08;Tasks Table&#xff09;订单表&#xff08;Orders Table&#xff09;评价表&#xff08;Reviews Table&#xff09; 3. 功能实现创建代办任务前端部分后端部分 接受代办任务前端…

产品经理-需求收集(二)

1. 什么是需求 指在一定的时期中&#xff0c;一定场景中&#xff0c;无论是心理上还是生理上的&#xff0c;用户有着某种“需要”&#xff0c;这种“需要”用户自己不一定知道的&#xff0c;有了这种“需要”后用户就有做某件事情的动机并促使达到其某种目的&#xff0c;这也就…

FPGA实现多路并行dds

目录 基本原理 verilog代码 仿真结果​ 基本原理 多路并行dds&#xff0c;传统DDS的局限性在于输出频率有限。根据奈奎斯特采样定理&#xff0c;单路DDS的输出频率应小于系统时钟频率的一半。但是在很多地方&#xff0c;要使采样率保持一致&#xff0c;所以&#xff0c;为了…

【CTF Web】CTFShow web7 Writeup(SQL注入+PHP+进制转换)

web7 1 阿呆得到最高指示&#xff0c;如果还出问题&#xff0c;就卷铺盖滚蛋&#xff0c;阿呆心在流血。 解法 注意到&#xff1a; <!-- flag in id 1000 -->拦截很多种字符&#xff0c;连 select 也不给用了。 if(preg_match("/\|\"|or|\||\-|\\\|\/|\\*|\…

路径规划算法的复杂度

通常通过以下指标来衡量&#xff1a; 时间复杂度&#xff1a;这是评估算法执行所需时间的量度。它通常用大O符号表示&#xff0c;给出了算法运行时间随着输入规模增长的增长率。例如&#xff0c;一个时间复杂度为O(n^2)的算法在处理大规模输入时会比时间复杂度为O(n log n)的算…

PostgreSQL的扩展(extensions)-常用的扩展之pg_plan_advsr

PostgreSQL的扩展&#xff08;extensions&#xff09;-常用的扩展之pg_plan_advsr pg_plan_advsr 是 PostgreSQL 社区中的一个扩展&#xff0c;用于分析和改进查询执行计划。它能够自动识别哪些查询执行缓慢&#xff0c;并提供优化建议&#xff0c;以提高查询性能。pg_plan_ad…

AI时代存储大战,NAND闪存市场风云再起!

随着人工智能&#xff08;AI&#xff09;相关半导体对高带宽存储&#xff08;HBM&#xff09;需求的推动&#xff0c;NAND闪存市场也感受到了这一趋势的影响。 据《Business Korea》援引行业消息来源称&#xff0c;NAND闪存市场的竞争正在加剧&#xff0c;而存储巨头三星和SK海…

CSP俄罗斯方块(简单易懂)

开始将题目理解成了&#xff0c;开始的列应该是从输入图案的最左端开始计算&#xff0c;将前面所有的空列都删掉&#xff0c;代码如下&#xff1a; #include<bits/stdc.h> using namespace std; const int N 1e410; const int M 1e510; int a[20][20]; int b[5][5];int…