pom文件
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.20</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
yml
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
url:
username:
password:
driver-class-name: com.mysql.cj.jdbc.Driver
##初始连接数,默认0
initialSize: 10
#最大连接数,默认8
maxActive: 30
#最小连接数,
minIdle: 10
#获取连接的最大等待时间,单位毫秒
maxWait: 2000
#缓存PreparedStatement,默认false 预编译 防注入
poolPreparedStatements: true
#缓存PreparedStatement的最大数量,默认-1(不缓存)。大于0时会自动开启缓存?PreparedStatement,所以可以省略上一句设置
maxOpenPreparedStatements: 20
filters: stat,wall,log4j
Config
@ConfigurationProperties("spring.datasource") //指定前缀
@Configuration //也可以使用@Configuration,@Configuration包含了@Component
@Data
public class DruidConfig {
//属性名要与springboot配置文件中属性名一致
private String url;
private String driverClassName;
private String username;
private String password;
private int initialSize;
private int maxActive;
private int minIdle;
private int maxWait;
private boolean poolPreparedStatements;
private int maxOpenPreparedStatements;
private String filters;
@Bean //放到Spring容器中
// @Primary //声明为主数据源,如果配置了多个数据源,未显式指定使用哪个数据源时,自动使用主数据源
public DataSource dataSource() throws SQLException {
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(url);
datasource.setDriverClassName(driverClassName);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setInitialSize(initialSize);
datasource.setMaxActive(maxActive);
datasource.setMinIdle(minIdle);
datasource.setMaxWait(maxWait);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setMaxOpenPreparedStatements(maxOpenPreparedStatements);
datasource.setFilters(filters);
return datasource;
}
@Bean
public ServletRegistrationBean setStatViewServlet(){
ServletRegistrationBean beanServlet = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String,String> initParams = new HashMap<>();
initParams.put("loginUsername","test");
initParams.put("loginPassword","654321");
initParams.put("allow",""); /**默认就是允许所有访问*/
beanServlet.setInitParameters(initParams);
return beanServlet;
}
//注册一个filters
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new WebStatFilter());
Map<String, String> initParams = new HashMap<>();
initParams.put("exclusions", "*.js,*.css,/druid/*");
registrationBean.setInitParameters(initParams);
registrationBean.setUrlPatterns(Arrays.asList("/*"));
return registrationBean;
}
}
监控地址??http://localhost:8911/druid/sql.html
?
|