一、druid数据源
1.1 为什么使用druid数据源
虽然HikariDataSource数据源性能比druid数据源好,但是druid数据源有成套的监控,安全等解决方案。
1.2 加入druid依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.17</version>
</dependency>
1.3 配置文件中指定数据源
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
1.4 查看数剧源
- 在test目录下
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Autowired
DataSource dataSource;
@Test
public void DataOrigin() throws SQLException {
System.out.println(dataSource.getClass());
//测试数据源是否连接
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
}
输出:
1.5 设置数据源其他属性
直接在配置文件里配置不起作用,因为没有类属性与之对应,要让配置起作用就得配置配置类。
- 配置文件中的配置:
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.filters=stat,wall,log4j
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.useGlobalDataSourceStat=true
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
- 配置类
把pring.datasource前缀的所有属性与我们新建的DruidDataSource类对象的属性绑定
@Configuration
public class DruidConfig {
//把pring.datasource前缀的所有属性绑定进来,配置文件中配置的属性是DruidDataSource
//这个数据库连接池的属性
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
//我们创建一个数据源,并加在容器中
public DataSource druid(){
return new DruidDataSource();
}
- 可能需要加入log4j的依赖
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
二、配置druid的监控
2.1 配置一个管理后台的Servlet
用ServletRegistrationBean 来注册Servlet
@Bean
//配置Druid的监控
//1.配置一个管理后台的Servlet(StatViewServlet)
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
Map<String, String> map = new HashMap<>();
//登录后台用户名
map.put("loginUsername","admin");
//登录后台密码
map.put("loginPassword","admin");
//允许谁登录
map.put("allow","localhost");
//拒绝谁访问
map.put("deny","172.18.0.3");
bean.setInitParameters(map);
return bean;
}
2.2 配置一个web监控的Filter
@Bean
//配置一个监控的Filter(webStatFilter)
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
//注册哪个Fileter就把哪个Filter设置进去
bean.setFilter(new WebStatFilter());
Map<Object, Object> map = new HashMap<>();
//不拦截哪些请求
map.put("exclusions","*.js,*.css,/druid/*");
//设置初始化参数
bean.setInitParameters(map);
//拦截的请求
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}`在这里插入代码片`
2.3 访问出现404
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),"/drud/*");
这里的druid写成duid