SpringBoot【1】集成 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.3.12.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 ,如下将会有返回。
在这里插入图片描述

抱歉,SpringBoot 3.0 目前还没有正式发布。但是,我可以给你提供 SpringBoot 2.x 版本集成 Druid 数据库连接池的代码示例。 首先,在 pom.xml 文件中添加以下依赖: ```xml <!-- Druid 数据库连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.5</version> </dependency> ``` 然后,在 application.properties 文件中添加以下配置: ```properties # 数据库连接配置 spring.datasource.url=jdbc:mysql://localhost:3306/dbname?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # Druid 连接池配置 spring.datasource.druid.initial-size=5 spring.datasource.druid.min-idle=5 spring.datasource.druid.max-active=20 spring.datasource.druid.test-on-borrow=true spring.datasource.druid.test-on-return=false spring.datasource.druid.test-while-idle=true spring.datasource.druid.validation-query=SELECT 1 spring.datasource.druid.filters=stat,wall,log4j spring.datasource.druid.connection-properties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 ``` 最后,在启动类中加上 `@EnableTransactionManagement` 注解来开启事务支持,并将数据源设置为 Druid 数据源: ```java @SpringBootApplication @EnableTransactionManagement public class YourApplication { @Bean @ConfigurationProperties(prefix = "spring.datasource.druid") public DataSource dataSource() { return DruidDataSourceBuilder.create().build(); } public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } } ``` 以上就是 SpringBoot 集成 Druid 的基本配置。你可以根据自己的实际情况进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值