【无标题】

1、配置application.yaml

spring:
  datasource:
      username: root
      password: root
      url: jdbc:mysql://localhost:3306/blog?characterEncoding=utf-8&serverTimezone=GMT%2B8
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.jdbc.Driver

      initialSize: 5
      minIdle: 5
      maxActive: 20
      maxWait: 60000
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 1 FROM DUAL
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      # 打开PSCache
      poolPreparedStatements: true
      #配置监控统计拦截的filters,stat:监控统计、slf4j:日志记录、wall:防御sql注入
      filters: stat,wall,log4j,config
      #指定每个连接上PSCache的大小
      maxPoolPreparedStatementPerConnectionSize: 20
      #合并多个DruidDataSource的监控数据
      useGlobalDataSourceStat: true
      #通过connectProperties属性来打开mergeSql功能;慢SQL记录
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

2、编写druid配置类

package com.example.demo.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.servlet.ServletRegistration;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DruidConfig {
    //注入application.yaml文件的配置
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource(){
        return new DruidDataSource();
    }

    //druid后台管理设置
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");

        //后台有人登陆,账号密码设置
        Map<String,String> map=new HashMap<>();

        //增加配置
        map.put("loginUsername","admin");
        map.put("loginPassword","123");
        map.put("allow","");
        //禁止访问
        //map.put("name","IP");
        //map.put("admin","127.0.0.1");

        bean.setInitParameters(map);
        return bean;
    }
}

3、访问路径

http://localhost:8080/druid

【无标题】

上一篇:花1w+买的Python零基础入门指南,花了钱的真香


下一篇:Spring 单元测试