简介
Druid是一个关系型数据库连接池,它是阿里巴巴的一个开源项目。Druid支持所有JDBC兼容的数据库,包括Oracle、MySQL、Derby、PostgreSQL、SQL Server、H2等。Druid在监控、可扩展性、稳定性和性能方面具有明显的优势。通过Druid提供的监控功能,可以实时观察数据库连接池和SQL查询的工作情况。使用Druid连接池,在一定程度上可以提高数据库的访问性能。
本博文采用的gradle方式构建的springboot项目,因此导入jar包也是以gradle方式。
一:创建boot项目,导入druid依赖
dependencies { compile 'org.springframework.boot:spring-boot-starter-web' compile 'org.mybatis.spring.boot:mybatis-spring-boot-starter:1.1.1' compile 'mysql:mysql-connector-java:5.1.37' compile 'com.alibaba:druid:1.0.27' }
二:在application-dev.yaml中配置druid属性
spring: datasource: dialect: mysql url: 'jdbc:mysql://127.0.0.1:3306/test_db?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&tinyInt1isBit=false' username: 'admin' password: 'admin' driver-class-name: 'com.mysql.jdbc.Driver' type: com.alibaba.druid.pool.DruidDataSource initialSize: 1 minIdle : 5 maxActive: 10 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 'x' testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize: 20 filters: stat,wall,slf4j connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 useGlobalDataSourceStat: true monitorUserName: admin monitorPassword: admin resetEnable: false allow: deny: exclusions: session: store-type: none #springboot默认session存储在redis中,由于本项目暂时未配置redis;故设置store-type:none
三:自定义数据库连接池(可跳过)
package com.chenpt.config; import com.alibaba.druid.pool.DruidDataSource; import org.mybatis.spring.annotation.MapperScan; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.bind.RelaxedPropertyResolver; import org.springframework.context.ApplicationContextException; import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.util.StringUtils; import javax.annotation.Resource; import java.sql.SQLException; import java.util.Arrays; /** * Created by admin on 2017/1/18. */ @Configuration @EnableTransactionManagement @MapperScan(value = "com.chenpt") public class DatabaseConfiguration implements EnvironmentAware { /** * 日志记录器 */ private static final Logger logger = LoggerFactory.getLogger(DatabaseConfiguration.class); @Resource private Environment env; private RelaxedPropertyResolver resolver; @Override public void setEnvironment(Environment environment) { this.env = environment; this.resolver = new RelaxedPropertyResolver(environment,"spring.datasource."); } //注册dataSource @Bean(initMethod = "init", destroyMethod = "close") public DruidDataSource dataSource() throws SQLException { if (StringUtils.isEmpty(resolver.getProperty("url"))) { logger.error("Your database connection pool configuration is incorrect!" + " Please check your Spring profile, current profiles are:" + Arrays.toString(env.getActiveProfiles())); throw new ApplicationContextException( "Database connection pool is not configured correctly"); } DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setDriverClassName(resolver.getProperty("driver-class-name")); druidDataSource.setUrl(resolver.getProperty("url")); druidDataSource.setUsername(resolver.getProperty("username")); druidDataSource.setPassword(resolver.getProperty("password")); druidDataSource.setInitialSize(Integer.parseInt(resolver.getProperty("initialSize"))); druidDataSource.setMinIdle(Integer.parseInt(resolver.getProperty("minIdle"))); druidDataSource.setMaxActive(Integer.parseInt(resolver.getProperty("maxActive"))); druidDataSource.setMaxWait(Integer.parseInt(resolver.getProperty("maxWait"))); druidDataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(resolver.getProperty("timeBetweenEvictionRunsMillis"))); druidDataSource.setMinEvictableIdleTimeMillis(Long.parseLong(resolver.getProperty("minEvictableIdleTimeMillis"))); druidDataSource.setValidationQuery(resolver.getProperty("validationQuery")); druidDataSource.setTestWhileIdle(Boolean.parseBoolean(resolver.getProperty("testWhileIdle"))); druidDataSource.setTestOnBorrow(Boolean.parseBoolean(resolver.getProperty("testOnBorrow"))); druidDataSource.setTestOnReturn(Boolean.parseBoolean(resolver.getProperty("testOnReturn"))); druidDataSource.setPoolPreparedStatements(Boolean.parseBoolean(resolver.getProperty("poolPreparedStatements"))); druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(Integer.parseInt(resolver.getProperty("maxPoolPreparedStatementPerConnectionSize"))); druidDataSource.setFilters(resolver.getProperty("filters")); return druidDataSource; } @Bean public PlatformTransactionManager transactionManager() throws SQLException { return new DataSourceTransactionManager(dataSource()); } }
四:配置druid(关键性配置)
package com.chenpt.config; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.bind.RelaxedPropertyResolver; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import javax.annotation.Resource; import java.util.HashMap; import java.util.Map; /** * @Author: ch * @Description: * @Date: created in 2018/7/26 * @Modified By: */ @Configuration public class DruidConfigration implements EnvironmentAware { @Resource Environment environment; /** * 日志记录器 */ private static final Logger logger = LoggerFactory.getLogger(DruidConfigration.class); private RelaxedPropertyResolver resolver; @Override public void setEnvironment(Environment environment) { this.environment = environment; this.resolver = new RelaxedPropertyResolver(environment,"spring.datasource."); } @Bean public ServletRegistrationBean druidServlet() { logger.info("init Druid Servlet Configuration "); ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(); servletRegistrationBean.setServlet(new StatViewServlet()); servletRegistrationBean.addUrlMappings("/druid/*"); Map<String, String> initParameters = new HashMap<>(); initParameters.put("loginUsername", resolver.getProperty("monitorUserName"));// 用户名 initParameters.put("loginPassword",resolver.getProperty("monitorPassword"));// 密码 // 禁用HTML页面上的“Reset All”功能 initParameters.put("resetEnable", resolver.getProperty("resetEnable")); // IP白名单 (没有配置或者为空,则允许所有访问) initParameters.put("allow", resolver.getProperty("allow")); //IP黑名单 (存在共同时,deny优先于allow) initParameters.put("deny", resolver.getProperty("deny")); servletRegistrationBean.setInitParameters(initParameters); return servletRegistrationBean; } @Bean public FilterRegistrationBean filterRegistrationBean() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(new WebStatFilter()); filterRegistrationBean.addUrlPatterns("/*"); filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); return filterRegistrationBean; } }
到此数据库配置就完成了,接下来启动程序,可以登录druid监控中心(http://localhost:8767/druid/login.html)
详情页