从零开始构建Spring Boot项目--配置数据源

整合Druid

1、引入jar包


<dependency>
    <groupId>com.alibabagroupId>
    <artifactId>druidartifactId>
    <version>1.2.5version>
dependency>

2、yml里面配置数据源

# 配置连接数据库
spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://192.168.1.1:3306/csjdbc
    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
    poolPreparedStatements: true
    maxPoolPreparedStatementPerConnectionSize: 20
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

3、配置Druid

由于Druid暂时不在Spring Boot中的直接支持,故需要进行配置信息的定制

我们在项目中创建一个config文件创建一个DruidConfig用来配置信息定制

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid(){
        return new DruidDataSource();
    }

    //配置Druid的监控
    //1、配置一个管理后台的Servlet
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String,String> inintParams = new HashMap<>();
        //登录名称
        inintParams.put("loginUsername","admin");
        //密码
        inintParams.put("loginPassword","123456");
        //允许谁登录设置
        inintParams.put("allow","localhost");//如果不设置访问,默认就是允许所有访问
        //拒绝谁来访问
        inintParams.put("deny","192.168.1.1");//不设置就没有,如果设置比如192.168.1.1 不能访问
        bean.setInitParameters(inintParams);
        return bean;
    }
    //2、配置一个web监控的filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        Map<String,String> inintParams = new HashMap<>();
        //添加需要忽略的格式
        inintParams.put("exclusions","*.js,*.css,/druid/*");
        bean.setInitParameters(inintParams);
        //添加需要过滤的规则
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }
}

查看druid
从零开始构建Spring Boot项目--配置数据源_第1张图片
用户密码就是自己设置的

//登录名称
 inintParams.put("loginUsername","admin");
 //密码
 inintParams.put("loginPassword","123456");

可以在页面监控一下信息
从零开始构建Spring Boot项目--配置数据源_第2张图片

你可能感兴趣的:(spring,spring,boot,java)