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.pswp.cn/web/15841.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/15841.shtml
英文地址,請注明出處:http://en.pswp.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…