1.springboot默认连接池
习惯使用springboot的小伙伴通过开始学习springboot链接数据库时,都会尝试着官方文档来 学习,所以springboot默认支持的数据库连接池c3p0和 dhcp,大家应该都很熟悉了吧,只需要在.propeties文件中配置下数据库连接字符串即可,默认采用c3p0链接池进行连接数据库,但是今天我着重记录的并非官方默认支持的链接池,而是集成性能不错的阿里数据源druid。
2.阿里连接池druid介绍
Druid介绍
Druid是一个JDBC组件,druid 是阿里开源在 github 上面的数据库连接池,它包括三部分:
* DruidDriver 代理Driver,能够提供基于Filter-Chain模式的插件体系。
* DruidDataSource 高效可管理的数据库连接池。
* SQLParser 专门解析 sql 语句
Druid 有什么优点?
1. 可以监控数据库访问性能,Druid内置提供了一个功能强大的StatFilter插件,能够详细统计SQL的执行性能,这对于线上分析数据库访问性能有帮助。
2. 替换DBCP和C3P0。Druid提供了一个高效、功能强大、可扩展性好的数据库连接池。
3. 数据库密码加密。直接把数据库密码写在配置文件中,这是不好的行为,容易导致安全问题。DruidDruiver和DruidDataSource都支持PasswordCallback。
4. SQL执行日志,Druid提供了不同的LogFilter,能够支持Common-Logging、Log4j和JdkLog,你可以按需要选择相应的LogFilter,监控你应用的数据库访问情况。
5. 扩展JDBC,如果你要对JDBC层有编程的需求,可以通过Druid提供的Filter-Chain机制,很方便编写JDBC层的扩展插件
3.druid加解密浅析
首先我们来看下 druid加密的过程
通过命令:
java -cp druid-1.0.16.jar com.alibaba.druid.filter.config.ConfigTools you_password
返回值如下:publickey代表公钥,privatekey是密码加密后的结果
privateKey:MIIBVgIBADANBgkqhkiG9w0BAQEFAASCAUAwggE8AgEAAkEA6+4avFnQKP+O7bu5YnxWoOZjv3no4aFV558HTPDoXs6EGD0HP7RzzhGPOKmpLQ1BbA5viSht+aDdaxXp6SvtMQIDAQABAkAeQt4fBo4SlCTrDUcMANLDtIlax/I87oqsONOg5M2JS0jNSbZuAXDv7/YEGEtMKuIESBZh7pvVG8FV531/fyOZAiEA+POkE+QwVbUfGyeugR6IGvnt4yeOwkC3bUoATScsN98CIQDynBXC8YngDNwZ62QPX+ONpqCel6g8NO9VKC+ETaS87wIhAKRouxZL38PqfqV/WlZ5ZGd0YS9gA360IK8zbOmHEkO/AiEAsES3iuvzQNYXFL3x9Tm2GzT1fkSx9wx+12BbJcVD7AECIQCD3Tv9S+AgRhQoNcuaSDNluVrL/B/wOmJRLqaOVJLQGg== publicKey:MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAOvuGrxZ0Cj/ju27uWJ8VqDmY7956OGhVeefB0zw6F7OhBg9Bz+0c84RjzipqS0NQWwOb4kobfmg3WsV6ekr7TECAwEAAQ==
4.springboot使用druid(废话少说直接上代码)
首先加入依赖如下:针对该依赖配置信息(由于springboot未能全面支持druid 所以需要配置datasource)
-
<dependency>
-
<groupId>com.alibaba
</groupId>
-
<artifactId>druid
</artifactId>
-
<version>1.0.20
</version>
-
</dependency>
# 驱动配置信息 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.url = jdbc:mysql://127.0.0.1:3306/myspringboot spring.datasource.username = your account spring.datasource.password = your encryt password spring.datasource.driverClassName = com.mysql.jdbc.Driver # 连接池的配置信息 # 初始化大小,最小,最大 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.testOnBorrow=false spring.datasource.testOnReturn=false # 打开PSCache,并且指定每个连接上PSCache的大小 spring.datasource.poolPreparedStatements=true spring.datasource.maxPoolPreparedStatementPerConnectionSize=20 # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙 spring.datasource.filters=config,stat,wall,log4j # 通过connectProperties属性来打开mergeSql功能;慢SQL记录 spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000;config.decrpt=true;config.decrypt.key=your public key
/** * Created by wk on 2018/1/10. */ @Configuration @ConfigurationProperties(prefix= "spring.datasources") public class DataSourceConfig { private Logger logger = LoggerFactory. getLogger(DataSourceConfig. class); private String type; private String url; private String driverClassName; private String username; private String password; private Integer initialSize; private Integer minIdle; private Integer maxActive; private Integer maxWait; private Integer timeBetweenEvictionRunsMillis; private Integer minEvictableIdleTimeMillis; private String validationQuery; private Boolean testWhileIdle; private Boolean testOnBorrow; private Boolean testOnReturn; private Boolean poolPreparedStatements; private Integer maxPoolPreparedStatementPerConnectionSize; private String filters; private String connectionProperties; public String getDriverClassName() { return driverClassName; } public void setDriverClassName(String driverClassName) { this. driverClassName = driverClassName; } public String getType() { return type; } public void setType(String type) { this. type = type; } public String getUrl() { return url; } public void setUrl(String url) { this. url = url; } public String getUsername() { return username; } public void setUsername(String username) { this. username = username; } public String getPassword() { return password; } public void setPassword(String password) { this. password = password; } public Integer getInitialSize() { return initialSize; } public void setInitialSize(Integer initialSize) { this. initialSize = initialSize; } public Integer getMinIdle() { return minIdle; } public void setMinIdle(Integer minIdle) { this. minIdle = minIdle; } public Integer getMaxActive() { return maxActive; } public void setMaxActive(Integer maxActive) { this. maxActive = maxActive; } public Integer getMaxWait() { return maxWait; } public void setMaxWait(Integer maxWait) { this. maxWait = maxWait; } public Integer getTimeBetweenEvictionRunsMillis() { return timeBetweenEvictionRunsMillis; } public void setTimeBetweenEvictionRunsMillis(Integer timeBetweenEvictionRunsMillis) { this. timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; } public Integer getMinEvictableIdleTimeMillis() { return minEvictableIdleTimeMillis; } public void setMinEvictableIdleTimeMillis(Integer minEvictableIdleTimeMillis) { this. minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; } public String getValidationQuery() { return validationQuery; } public void setValidationQuery(String validationQuery) { this. validationQuery = validationQuery; } public Boolean getTestWhileIdle() { return testWhileIdle; } public void setTestWhileIdle(Boolean testWhileIdle) { this. testWhileIdle = testWhileIdle; } public Boolean getTestOnBorrow() { return testOnBorrow; } public void setTestOnBorrow(Boolean testOnBorrow) { this. testOnBorrow = testOnBorrow; } public Boolean getTestOnReturn() { return testOnReturn; } public void setTestOnReturn(Boolean testOnReturn) { this. testOnReturn = testOnReturn; } public Boolean getPoolPreparedStatements() { return poolPreparedStatements; } public void setPoolPreparedStatements(Boolean poolPreparedStatements) { this. poolPreparedStatements = poolPreparedStatements; } public Integer getMaxPoolPreparedStatementPerConnectionSize() { return maxPoolPreparedStatementPerConnectionSize; } public void setMaxPoolPreparedStatementPerConnectionSize(Integer maxPoolPreparedStatementPerConnectionSize) { this. maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize; } public String getFilters() { return filters; } public void setFilters(String filters) { this. filters = filters; } public String getConnectionProperties() { return connectionProperties; } public void setConnectionProperties(String connectionProperties) { this. connectionProperties = connectionProperties; } @Bean public ServletRegistrationBean druidServlet() { ServletRegistrationBean reg = new ServletRegistrationBean(); reg.setServlet( new StatViewServlet()); reg.addUrlMappings( "/druid/*"); reg.addInitParameter( "loginUsername", username); reg.addInitParameter( "loginPassword", password); return reg; } @Bean public FilterRegistrationBean filterRegistrationBean() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter( new WebStatFilter()); filterRegistrationBean.addUrlPatterns( "/*"); filterRegistrationBean.addInitParameter( "exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); filterRegistrationBean.addInitParameter( "profileEnable", "true"); return filterRegistrationBean; } @Bean @Primary public DataSource druidDataSource() { DruidDataSource datasource = new DruidDataSource(); datasource.setUrl( url); datasource.setUsername( username); datasource.setPassword( password); datasource.setDriverClassName( driverClassName); datasource.setInitialSize( initialSize); datasource.setMinIdle( minIdle); datasource.setMaxActive( maxActive); datasource.setMaxWait( maxWait); datasource.setTimeBetweenEvictionRunsMillis( timeBetweenEvictionRunsMillis); datasource.setMinEvictableIdleTimeMillis( minEvictableIdleTimeMillis); datasource.setValidationQuery( validationQuery); datasource.setTestWhileIdle( testWhileIdle); datasource.setTestOnBorrow( testOnBorrow); datasource.setTestOnReturn( testOnReturn); String paramArray[] = connectionProperties.split( ";"); datasource.setConnectionProperties( connectionProperties); try { datasource.setFilters( filters); } catch (SQLException e) { logger.error( "druid configuration initialization filter", e); } return datasource; } }
2.或者直接用druid-spring-boot-starter druid-spring-boot-starter项目
-
<dependency>
-
<groupId>com.alibaba
</groupId>
-
<artifactId>druid-spring-boot-starter
</artifactId>
-
<version>1.1.0
</version>
-
</dependency>
######Druid数据源配置###### | |
# JDBC配置 | |
spring.datasource.druid.url= # 或spring.datasource.url= | |
spring.datasource.druid.username= # 或spring.datasource.username= | |
spring.datasource.druid.password= # 或spring.datasource.password= | |
spring.datasource.druid.driver-class-name= #或 spring.datasource.driver-class-name= | |
# 连接池配置,下面配置说明请参考Druid Github Wiki,配置_DruidDataSource参考配置 | |
spring.datasource.druid.initial-size= | |
spring.datasource.druid.max-active= | |
spring.datasource.druid.min-idle= | |
spring.datasource.druid.max-wait= | |
spring.datasource.druid.pool-prepared-statements= | |
spring.datasource.druid.max-pool-prepared-statement-per-connection-size= | |
spring.datasource.druid.max-open-prepared-statements= #等价于上面的max-pool-prepared-statement-per-connection-size | |
spring.datasource.druid.validation-query= | |
spring.datasource.druid.validation-query-timeout= | |
spring.datasource.druid.test-on-borrow= | |
spring.datasource.druid.test-on-return= | |
spring.datasource.druid.test-while-idle= | |
spring.datasource.druid.time-between-eviction-runs-millis= | |
spring.datasource.druid.min-evictable-idle-time-millis= | |
spring.datasource.druid.max-evictable-idle-time-millis= | |
spring.datasource.druid.filters= #默认值stat,配置多个英文逗号分隔 | |
... | |
# 更多配置属性见 DruidDataSource 内成员变量(只要有set方法便支持),或者根据IDE提示,或者查看官方文档 | |
######Druid监控配置###### | |
#下面配置说明请参考Druid Github Wiki,配置_配置WebStatFilter | |
spring.datasource.druid.web-stat-filter.enabled= #是否启用StatFilter默认值true | |
spring.datasource.druid.web-stat-filter.url-pattern= | |
spring.datasource.druid.web-stat-filter.exclusions= | |
spring.datasource.druid.web-stat-filter.session-stat-enable= | |
spring.datasource.druid.web-stat-filter.session-stat-max-count= | |
spring.datasource.druid.web-stat-filter.principal-session-name= | |
spring.datasource.druid.web-stat-filter.principal-cookie-name= | |
spring.datasource.druid.web-stat-filter.profile-enable= | |
#下面配置说明请参考Druid Github Wiki,配置_StatViewServlet配置 | |
spring.datasource.druid.stat-view-servlet.enabled= #是否启用StatViewServlet默认值true | |
spring.datasource.druid.stat-view-servlet.url-pattern= | |
spring.datasource.druid.stat-view-servlet.reset-enable= | |
spring.datasource.druid.stat-view-servlet.login-username= | |
spring.datasource.druid.stat-view-servlet.login-password= | |
spring.datasource.druid.stat-view-servlet.allow= | |
spring.datasource.druid.stat-view-servlet.deny= | |
#下面配置说明请参考Druid Github Wiki,配置_Druid和Spring关联监控配置 | |
spring.datasource.druid.aop-patterns= #Spring监控AOP切入点,如x.y.z.service.*,配置多个英文逗号分隔 | |
#如果spring.datasource.druid.aop-patterns要代理的类没有定义interface请设置spring.aop.proxy-target-class=true |
原文连接:https://blog.csdn.net/ikownyou/article/details/79022560