SpringBoot【1】集成 Druid

news2024/9/20 6:32:39

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: 5826

spring:
  application:
    # 应用名称
    name: junjiu-springboot-druid
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://192.168.88.54:3306/ideadb?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=false
      username: fid_idea
      password: 123456
      initial-size: 10
      max-active: 100
      min-idle: 10
      max-wait: 60000
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 300000
      max-evictable-idle-time-millis: 600000
      validation-query: SELECT 1 FROM DUAL
      # validation-query-timeout: 5000
      test-on-borrow: false
      test-on-return: false
      test-while-idle: true
      connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
      #filters: #配置多个英文逗号分隔(统计,sql注入,log4j过滤)
      filters: stat,wall
      stat-view-servlet:
        enabled: true
        url-pattern: /druid/*

# 监控页面配置.
jj:
  druid:
    monitor:
      login-username: root
      login-password: 123456
      reset-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 {

    @Autowired
    DruidConfigProperty druidConfigProperty;

    @Autowired
    DruidMonitorProperty druidMonitorProperty;

    /**
     * Druid 连接池配置
     */
    @Bean
    public 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操作配置
     */
    @Bean
    public JdbcTemplate jdbcTemplate (@Autowired DruidDataSource dataSource){
        return new JdbcTemplate(dataSource) ;
    }

    /**
     * 配置 Druid 监控界面
     */
    @Bean
    public 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;
    }

    @Bean
    public 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 {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private 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.coloradmin.cn/o/1697263.html

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

相关文章

html5网页-浏览器中实现高德地图定位功能

介绍 HTML5是当前Web开发中最常用的技术之一&#xff0c;而地图应用又是其中一个非常常见的需求。高德地图是国内最受欢迎的地图服务提供商之一&#xff0c;他们提供了一系列的API&#xff0c;方便开发者在自己的网站或应用中集成地图功能。 接下来我们如何使用HTML5浏览器和高…

Unity开发——XLua热更新之Hotfix配置(包含xlua获取与导入)

一、Git上获取xlua 最新的xlua包&#xff0c;下载地址链接&#xff1a;https://github.com/Tencent/xLua 二、Unity添加xlua 解压xlua压缩包后&#xff0c;将xlua里的Assets里的文件直接复制进Unity的Assets文件夹下。 成功导入后&#xff0c;unity工具栏会出现xlua选项。 …

【C++提高编程-04】----C++之Vector容器实战

&#x1f3a9; 欢迎来到技术探索的奇幻世界&#x1f468;‍&#x1f4bb; &#x1f4dc; 个人主页&#xff1a;一伦明悦-CSDN博客 ✍&#x1f3fb; 作者简介&#xff1a; C软件开发、Python机器学习爱好者 &#x1f5e3;️ 互动与支持&#xff1a;&#x1f4ac;评论 &…

初步认识栈和队列

Hello&#xff0c;everyone&#xff0c;今天小编讲解栈和队列的知识&#xff01;&#xff01;&#xff01; 1.栈 1.1栈的概念及结构 栈&#xff1a;一种特殊的线性表&#xff0c;其只允许在固定的一端进行插入和删除元素操作。 进行数据插入和删除操作的一端 称为栈顶&…

Mysql 找出未提交事务的SQL及死锁

未提交事务&#xff1a; 通过查看information_schema.INNODB_TRX视图,您可以了解当前系统中正在运行的事务情况,从而进行问题排查和性能优化。 SELECT * FROM information_schema.innodb_trx; 通过trx_state为RUNNIG,trx_started判断是否有一直RUNNING的事务。 如果有未提交…

Linux修炼之路之冯系结构,操作系统

目录 一&#xff1a;冯诺依曼体系结构 1.五大组件 2.存储器存在的意义 3.几个问题 二&#xff1a;操作系统 接下来的日子会顺顺利利&#xff0c;万事胜意&#xff0c;生活明朗-----------林辞忧 一&#xff1a;冯诺依曼体系结构 我们当代的计算机的基本构成都是由冯诺依曼…

【深度学习】第1章

概论: 机器学习是对研究问题进行模型假设,利用计算机从训练数据中学习得到模型参数,并最终对数据进行预测和分析,其基础主要是归纳和统计。 深度学习是一种实现机器学习的技术,是机器学习重要的分支。其源于人工神经网络的研究。深度学习的模型结构是一种含多隐层的神经…

MySQL增删查改进阶

数据库约束表的关系增删查改 目录 一.数据库约束类型 NOT NULL约束类型 UNIQUE 唯一约束 DEFAULT 默认值约束 PRIMARY KEY&#xff1a;主键约束 FOREIGN KEY :W外键约束 二&#xff0c;查询 count&#xff08;&#xff09;两种用法 sum&#xff0c;avg&#xff0c;max…

python文件处理之os模块和shutil模块

目录 1.os模块 os.path.exists(path)&#xff1a;文件或者目录存在与否判断 os.path.isfile(path)&#xff1a;判断是否是文件 os.path.isdir(path)&#xff1a;判断是否是文件夹 os.remove(path)&#xff1a;尝试删除文件 os.rmdir(path)&#xff1a;尝试删除目录 os.m…

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

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

行为型设计模式之模板模式

文章目录 概述原理结构图实现 小结 概述 模板方法模式(template method pattern)原始定义是&#xff1a;在操作中定义算法的框架&#xff0c;将一些步骤推迟到子类中。模板方法让子类在不改变算法结构的情况下重新定义算法的某些步骤。 模板方法中的算法可以理解为广义上的业…

Linux驱动(3)- LInux USB驱动层次

在Linux系统中&#xff0c;提供了主机侧和设备侧USB驱动框架。 从主机侧&#xff0c;需要编写USB驱动包括主机控制器驱动&#xff0c;设备驱动两类&#xff0c;USB 主机控制驱动程序控制插入其中的USB设备。 USB设备驱动程序控制该设备如何作为从设备与主机进行通信。 1.主机…

文件夹打开出错?这里有你需要的数据恢复与预防指南

在日常使用电脑时&#xff0c;我们有时会遇到文件夹打开出错的情况。当你尝试访问某个文件夹时&#xff0c;系统可能会弹出一个错误提示&#xff0c;告诉你无法打开该文件夹。这种情况不仅会影响我们的工作效率&#xff0c;还可能导致重要数据的丢失。接下来&#xff0c;我们将…

Flutter-自定义折叠流布局实现

需求 在 Flutter 开发中&#xff0c;常常需要实现自定义布局以满足不同的需求。本文将介绍如何通过自定义组件实现一个折叠流布局&#xff0c;该组件能够显示一系列标签&#xff0c;并且在内容超出一定行数时&#xff0c;可以展开和收起。 效果 该折叠流布局可以显示一组标签…

ROCm上运行Transformer

10.7. Transformer — 动手学深度学习 2.0.0 documentation (d2l.ai) 代码 import math import pandas as pd import torch from torch import nn from d2l import torch as d2l#save class PositionWiseFFN(nn.Module):"""基于位置的前馈网络""&qu…

【uni-best+UView】使用mitt实现自定义错误对话框

痛点 目前在设计一个uni-best的前端全局的异常提示信息&#xff0c;如果采用Toast方式&#xff0c;对微信支持的不友好。微信的7中文长度连个NPE信息都无法完整显示&#xff0c;更不用提Stacktrace的复杂报错了。如果使用对话框&#xff0c;必须在页面先预先定义&#xff0c;对…

C/C++ 进阶(2)多态

个人主页&#xff1a;仍有未知等待探索-CSDN博客 专题分栏&#xff1a;C 目录 一、多态的概念 二、多态的定义及其实现 1、多态的构成条件 2、虚函数 3、虚函数重写 a.常规 b.两个例外 1、协变&#xff08;基类与派生类虚函数返回值类型不同&#xff09; 2、析构函数重…

10G UDP协议栈 (9)UDP模块

目录 一、UDP协议简单介绍 二、UDP功能实现 三、仿真 一、UDP协议简单介绍 UDP协议和TCP协议同位于传输层&#xff0c;介于网络层&#xff08;IP&#xff09;和应用层之间&#xff1a;UDP数据部分为应用层报文&#xff0c;而UDP报文在IP中承载。 UDP 报文格式相对于简单&am…

单工无线发射接收系统

1 绪论 随着无线电技术的发展,通讯方式也从传统的有线通讯逐渐转向无线通讯。由于传统的有线传输系统有配线的问题,较不便利,而无线通讯具有成本廉价、建设工程周期短、适应性好、扩展性好、设备维护容易实现等特点,故未来通讯方式将向无线传输系统方向发展。同时,实现系…