SpringBoot使用Druid数据源
导入druid依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
yaml配置文件
spring:
datasource:
username: root
password: root
#假如时区报错,就增加一个时区的配置就ok了,serverTimezone=UTC
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#SpringBoot默认是不注入这些的,需要自己绑定
#druid数据源专有配置
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
#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许报错,java.lang.ClassNotFoundException: org.apache.Log4j.Properity
#则导入log4j 依赖就行
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
druid配置文件
package com.ji.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.Filter;
import javax.servlet.ServletRegistration;
import javax.sql.DataSource;
import java.util.HashMap;
@Configuration
public class DruidConfig{
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource(){
return new DruidDataSource ();
}
//后台监控 web.xml
//因为SpringBoot内置了Servlet容器所有没有web.xml,替代方法ServletRegistrationBean
@Bean
public ServletRegistrationBean statViewServlet(){
//后台需要有人登录账号密码
HashMap<String, String> initParams = new HashMap<> ();
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<> (new StatViewServlet (), "/druid/*");
//增加配置
initParams.put ("loginUsername","admin"); //登录key是固定的
initParams.put ("loginPassword","123456");
//允许谁可以访问
initParams.put ("allow","");//""谁都可以访问
//禁止谁能访问呢
//initParams.put ("jsp","ip地址")
bean.setInitParameters (initParams);//设置初始化参数
return bean;
}
//filter 过滤器
@Bean
public FilterRegistrationBean webStartFilter(){
FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<> ();
bean.setFilter (new WebStatFilter ());
//可以过滤那些请求
HashMap<String, String> initParams = new HashMap<> ();
initParams.put ("exclusions","*.js,*.css,/druid/*");//这些东西不通行
return bean;
}
}