SpringBoot切换为Druid数据源

x33g5p2x  于2021-03-14 发布在 Spring  
字(4.2k)|赞(0)|评价(0)|浏览(415)

SpringBoot默认的数据源为com.zaxxer.hikari.HikariDataSource,虽然该数据源比阿里的Druid性能高,但是Druid数据源提供了一套安全的机制和监控,所以开发中常用Druid而不是hikari。
1. 引入Druid数据源
pom.xml

<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.2</version>
</dependency>

2. 切换到Druid数据源
application.yml

spring:
  datasource:
    username: root
    password: admin
    url: jdbc:mysql://127.0.0.1:3306/learn?useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

3. 测是否切换到了Druid数据源
com/exa/jdbc/JdbcApplicationTests.java

package com.exa.jdbc;

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 JdbcApplicationTests {

    @Autowired
    DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {
        System.out.println("dataSource="+dataSource.getClass());
        Connection connection = dataSource.getConnection();
        System.out.println("Connection="+connection);
        connection.close();
    }
}

日志输入如下:

// 成功切换到Druid数据源了
dataSource=class com.alibaba.druid.pool.DruidDataSource
Connection=com.mysql.jdbc.JDBC4Connection@2a4f5433

我们可以再添加一些配置,如下:
application.yml

spring:
  datasource:
    username: root
    password: admin
    url: jdbc:mysql://127.0.0.1:3306/learn?useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poo1PreparedStatements: true
    # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall 用于防火墙
    filters: stat ,wall, log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

新添加的属性在数据源属性类DataSourceProperties上是没有的,所以我们需要自定义一个配置类,将上面这些新增的属性生效,我们还可以开启监控。
com/exa/config/DruidConfig.java

package com.exa.jdbc.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 {

    /**
     * 让新增的配置生效
     */
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid() {
        return new DruidDataSource();
    }

    /*
     * 配置Druid监控(如果仅仅是让新增的配置属性生效不需要配置监控,只是我把它一起做了个笔记放在这)
     * 1. 配置一个管理后台的Servlet
     * 2. 配置一个监控的filter
     */

    /**
     * 1. 配置一个管理后台的Servlet
     */
    @Bean
    public ServletRegistrationBean servletRegistrationBean() {
        // 监控 /druid/的请求,这就是后台的路径
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String, String> initParams = new HashMap<>();
        // 你可查看StatViewServlet做一些基础配置,如下
        // 登录后台的用户名和密码
        initParams.put("loginUsername", "admin");
        initParams.put("loginPassword", "123456");
        // 允许localhost访问,如果不设置默认所有人可访问
        initParams.put("allow", "localhost");
        // 拒绝该ip地址访问
        initParams.put("deny", "192.168.15.21");
        bean.setInitParameters(initParams);
        return bean;
    }

    /**
     * 2. 配置一个监控的filter
     */
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        // 将要注册的Filter添加
        bean.setFilter(new WebStatFilter());

        // 在WebStatFilter你可以看到可以做一些基础配置
        Map<String, String> initParams = new HashMap<>();
        // 不拦截*.js,*.css,/druid/的请求
        initParams.put("exclusions", "*.js,*.css,/druid/*");
        bean.setInitParameters(initParams);
        // 拦截所有请求
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }
}

定义好上面的DruidConfig配置类后,新增的属性就生效了。除此之外还配置了Druid后台监控,当你访问:http://localhost:8080/druid/ 并输入在DruidConfig中设置的用户名和密码就可以进入如下后台:

相关文章

热门文章

更多