前言

使用关系型数据库一般都会随着业务的迅速增长、数据量增大,数据库的性能出现下降,监控并提升数据库的访问性能就显得格外重要。


一、Druid是什么?

Druid是一个关系型数据库的连接池,是阿里巴巴的一个开源项目。Druid支持所有JDBC兼容数据库,例如Oracle、mysql、sql server等,在项目中使用Druid,可以实时查看sql执行情况、检测出比较慢的查询等,从而做出相应的优化

提示:这里对文章进行总结:本文以Springboot项目为例,在springboot项目基础上配置Druid

二、使用步骤

1.配置Druid的依赖

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

2.配置application.yml

代码如下(示例):

server:
   port: 8084
   tomcat:
      max-http-header-size: 1048576  #请求头最大长度
      max-http-post-size: 2097152    #请求体最大长度
   servlet:
      session:
         timeout: 36000s      #session失效时间
spring:
   application:
      name: project
   thymeleaf:
      mode: HTML5
   datasource:  #mysql账号信息
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2B8
      username: root
      password: 123456
      #数据源其他配置
      #配置初始化大小、最小、最大线程数
      initialSize: 5
      minIdle: 5
      #CPU核数+1,也可以大些但不要超过20,数据库加锁时连接过多性能下降
      maxActive: 20
      #最大等待时间,内网:800,外网:1200(三次握手1s)
      maxWait: 60000
      timeBetweenEvictionRunsMillis: 60000
      #配置一个连接在池中最大空间时间,单位是毫秒
      minEvictableIdleTimeMillis: 300000
      testWhileIdle: true
      #设置从连接池获取连接时是否检查连接有效性,true检查,false不检查
      testOnBorrow: true
      #设置从连接池归还连接时是否检查连接有效性,true检查,false不检查
      testOnReturn: true
      #可以支持PSCache(提升写入、查询效率)
      poolPreparedStatements: true
      #配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
      filters: stat,wall,log4j
      #保持长连接
      keepAlive: true
      maxPoolPreparedStatementPerConnectionSize: 20
      useGlobalDataSourceStat: true
      #慢查询记录
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

3.配置Druid监控器和服务器

代码如下(示例):定义Druid监控和过滤器,设定访问的黑白名单、配置监控登录账号密码,这个过程也可以在application.yml中配置,本文不做介绍

/**
 * springboot监控
 */
@Configuration
public class DruidConfiguration {

	@Bean
	public ServletRegistrationBean statViewServlet() {
		ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),
				"/druid/*");
		// 白名单:
		servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
		// 黑名单
		servletRegistrationBean.addInitParameter("deny", "192.168.0.120");
		// 登录账号+密码.
		servletRegistrationBean.addInitParameter("loginUsername", "druid");
		servletRegistrationBean.addInitParameter("loginPassword", "druid123");
		// 是否能够重置数据.
		servletRegistrationBean.addInitParameter("resetEnable", "false");
		return servletRegistrationBean;
	}

	@Bean
	public FilterRegistrationBean statFilter() {
		FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
		// 添加过滤规则.
		filterRegistrationBean.addUrlPatterns("/");
		// 添加忽略过滤文件格式
		filterRegistrationBean.addInitParameter("exclusions", ".js,.css,.gif,.jpg,.png,.ico,/druid/");
		return filterRegistrationBean;
	}

	@Bean
	PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor() {
		return new PersistenceExceptionTranslationPostProcessor();
	}

	// 配置数据库的基本链接信息
	@Bean(name = "dataSource")
	@Primary
	@ConfigurationProperties(prefix = "spring.datasource")
	// 可以在application.properties中直接导入
	public DataSource dataSource() {
		return DataSourceBuilder.create().type(com.alibaba.druid.pool.DruidDataSource.class).build();
	}

	@Bean
	public SqlSessionFactoryBean sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		bean.setMapperLocations(resolver.getResources("classpath:/mapper/*.xml"));
		return bean;
	}
}

开启监控功能,运行项目,访问地址:localhost:8084/druid/index.html即可打开控制台,如果是项目本身做了登录验证,可以先登录本项目后再登录监控控制界面

java druid配置优化 druid性能调优_sql

总结

Druid在用户使用系统过程中,会不断收集sql执行次数、时间花费、并发等情况,帮助我们在线诊断数据库的访问性能。这里只是根据自己使用的情况做一个简单的介绍,详细信息还请阅读官网源码。