springboot 整合Druid

过程

1、导入包

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.12</version>
</dependency>

2、配置application.yml文件

spring:
  datasource:
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/mybatisplus?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
    # 配置数据源
    type: com.alibaba.druid.pool.DruidDataSource

3、创建 config 文件夹

package com.wt.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import org.springframework.boot.context.properties.ConfigurationProperties;
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.HashMap;

@Configuration
public class MyDruidConfig {
    @ConfigurationProperties("spring.datasource")
    @Bean
    public DataSource druidSource(){
        return new DruidDataSource();
    }
    // 后台监控
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/**");
        HashMap<String, String> hashMap = new HashMap<>();
        // 增加配置
        hashMap.put("loginUsername", "admin");  //登录的key 是固定的
        hashMap.put("loginPassword", "1231300");
        // 允许谁访问
        hashMap.put("allow", "localhost");

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

 

    public FilterRegistrationBean webFilter(){
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new WebStatFilter());
        HashMap<String, String> initParameters = new HashMap<>();
        // 填写代码

        bean.setInitParameters(initParameters);

        return bean;
    }

 

posted @ 2020-07-24 23:36  市丸银  阅读(174)  评论(0编辑  收藏  举报