背景
通过前面的文章已经讲述了SpringCloud+nacos服务的搭建:传送门springCloud alibaba+nacos模块化项目搭建
当搭建好基础服务后,肯定会有数据库操作。目前常用的连接池,springboot自带的hicari-CP连接池和阿里巴巴的Druid连接池。Druid连接池提供了可视化的监控界面,因此我选择了Druid。当然hicari-CP也提供了插件感兴趣可以去了解一下:p6spy插件。hicari-CP的性能是高于druid的。感兴趣的可以去百度相关文章了解一下,我就不在这多说。接下来直接上干货。此文章跳过了对mybatis的集成
pom依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
配置文件
spring:
#数据库配置
datasource:
url: jdbc:mysql://127.0.0.1:3306/zhuiri?useUnicode=true&useSSL=false&characterEncoding=utf-8&serverTimezone=UTC
username: root
password: root
# 使用druid数据源
name: mysql
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
#连接池初始化大小,最小值,最大值,
initial-size: 5
min-idle: 5
max-active: 100
#获取连接超时时间,单位:毫秒
max-wait: 10000
#是否缓存preparedStatement,对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭
pool-prepared-statements: false
#间隔多久检测一次需要关闭的空闲连接,单位:毫秒
time-between-eviction-runs-millis: 10000
#用来检测连接是否有效的sql
validation-query: SELECT 1 FROM DUAL
#检测连接是否有效的超时时间, 单位:秒
validation-query-timeout: 3
test-while-idle: true
#开启此配置会降低性能
test-on-borrow: false
test-on-return: false
#配置监控统计filter,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat
#配置监控统计filter的慢sql参数
filter:
stat:
log-slow-sql: true
slow-sql-millis: 80
merge-sql: true
servlet:
multipart:
max-file-size: 20MB
max-request-size: 50MB
可视化监控配置
@Configuration
public class DruidConfiguration {
/**
* 注册一个StatViewServlet
*
* @return
*/
@Bean
public ServletRegistrationBean DruidStatViewServle2() {
//org.springframework.boot.context.embedded.ServletRegistrationBean提供类的进行注册.
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
servletRegistrationBean.addUrlMappings("/druid/*");
//白名单:
servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
//IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page.
servletRegistrationBean.addInitParameter("deny", "192.168.1.73");
//登录查看信息的账号密码.
servletRegistrationBean.addInitParameter("loginUsername", "admin");
servletRegistrationBean.addInitParameter("loginPassword", "admin");
//是否能够重置数据.
servletRegistrationBean.addInitParameter("resetEnable", "false");
return servletRegistrationBean;
}
/**
* 注册一个:filterRegistrationBean
*
* @return
*/
@Bean
public FilterRegistrationBean druidStatFilter2() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
//添加过滤规则.
filterRegistrationBean.addUrlPatterns("/*");
//添加不需要忽略的格式信息.
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid2/*");
return filterRegistrationBean;
}
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
}
到这就集成好了,启动项目访问地址:http://localhost:8080/druid/login.html
剩下的登录进去,根据导航栏就可以解锁druid的功能啦!
如有问题,希望大家评论区留言多多指教!如觉得写得还可以,就给一个赞吧!