一、添加依赖
<!--mybatis-开始--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.2.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId >druid</artifactId> <version>1.0.26</version> </dependency> <!--mybatis-结束-->
二、配置application.properties
##################################mysql数据源配置################################## spring.datasource.url=jdbc:mysql://localhost/db_test?useUnicode=true&characterEncoding=utf-8 spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver #druid连接池 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
注意:其实到这里就可以正常使用了,但是如果想使用druid里的诸多属性,则需要添加支持类
三、添加druid的支持类
package com.example.demo.utils.configuration.druid; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DatabaseDriver; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.alibaba.druid.pool.DruidDataSource; /** * druid的支持类 * @Author: 我爱大金子 * @Description: druid的支持类 * @Date: Created in 12:48 2017/6/20 */ @Configuration public class DruidConfiguration { @ConditionalOnClass(DruidDataSource.class) @ConditionalOnProperty(name = "spring.datasource.type", havingValue = "com.alibaba.druid.pool.DruidDataSource", matchIfMissing = true) static class Druid extends DruidConfiguration { @Bean @ConfigurationProperties("spring.datasource.druid") public DruidDataSource dataSource(DataSourceProperties properties) { DruidDataSource druidDataSource = (DruidDataSource) properties.initializeDataSourceBuilder().type(DruidDataSource.class).build(); DatabaseDriver databaseDriver = DatabaseDriver.fromJdbcUrl(properties.determineUrl()); String validationQuery = databaseDriver.getValidationQuery(); if (validationQuery != null) { druidDataSource.setValidationQuery(validationQuery); } return druidDataSource; } } }
配置application.properties:
##################################mysql数据源配置################################## spring.datasource.url=jdbc:mysql://localhost/db_test?useUnicode=true&characterEncoding=utf-8 spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.type=com.alibaba.druid.pool.DruidDataSource #初始化连接大小 spring.datasource.druid.initial-size=8 #最小空闲连接数 spring.datasource.druid.min-idle=5 #最大连接数 spring.datasource.druid.max-active=10 #查询超时时间 spring.datasource.druid.query-timeout=6000 #事务查询超时时间 spring.datasource.druid.transaction-query-timeout=6000 #关闭空闲连接超时时间 spring.datasource.druid.remove-abandoned-timeout=1800
四、监控
4.1、配置servlet
package com.example.demo.utils.configuration.druid; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import com.alibaba.druid.support.http.StatViewServlet; /** * 监控-配置servlet * @Author: 我爱大金子 * @Description: 监控-servlet * @Date: Created in 12:50 2017/6/20 */ @WebServlet(urlPatterns = { "/druid/*" }, initParams = { @WebInitParam(name = "loginUsername", value = "liuy"), @WebInitParam(name = "loginPassword", value = "123456") }) public class DruidStatViewServlet extends StatViewServlet { private static final long serialVersionUID = 1L; }
4.2、配置filter
package com.example.demo.utils.configuration.druid; import javax.servlet.annotation.WebFilter; import javax.servlet.annotation.WebInitParam; import com.alibaba.druid.support.http.WebStatFilter; /** * 监控-配置filter * @Author: 我爱大金子 * @Description: 描述 * @Date: Created in 12:51 2017/6/20 */ @WebFilter(filterName = "druidWebStatFilter", urlPatterns = "/*", initParams = { @WebInitParam(name = "exclusions", value = "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*") }) public class DruidWebStatFilter extends WebStatFilter { }
测试:访问http://localhost:9090/druid/index.html
注意:此时还没有SQL监控与spring监控。
4.3、配置sql监控与spring监控
在application.properties文件中配置sql监控
#sql监控配置:filter类名:stat,config,encoding,logging spring.datasource.druid.filters=stat
spring监控配置
第一步:新建一个配置文件,如:druid-bean.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 配置_Druid和Spring关联监控配置 --> <bean id="druid-stat-interceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor"></bean> <!-- 方法名正则匹配拦截配置 --> <bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype"> <property name="patterns"> <list> <value>com.example.demo.mapper.*</value> </list> </property> </bean> <aop:config proxy-target-class="true"> <aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" /> </aop:config> </beans>
第二步:在启动类上加载druid-bean.xml文件
package com.example.demo; import com.example.demo.utils.filter.CustomFilter; import com.example.demo.utils.listener.CustomListener; import com.example.demo.utils.servlet.CustomServlet; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.*; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ImportResource; import javax.servlet.DispatcherType; import javax.servlet.ServletContext; import javax.servlet.ServletException; import java.util.EnumSet; @ServletComponentScan @SpringBootApplication @ImportResource(locations = { "classpath:druid-bean.xml" }) public class SpringbootDemo27Application { public static void main(String[] args) { SpringApplication.run(SpringbootDemo27Application.class, args); } }
重启服务,报异常:
解决:添加aop依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
重启服务
另一种实现方式
package com.liuy.demo.configuration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DatabaseDriver; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; @Configuration public class DruidConfiguration { @ConditionalOnClass(DruidDataSource.class) @ConditionalOnProperty(name = "spring.datasource.type", havingValue = "com.alibaba.druid.pool.DruidDataSource", matchIfMissing = true) static class Druid extends DruidConfiguration { @Bean @ConfigurationProperties("spring.datasource.druid") public DruidDataSource dataSource(DataSourceProperties properties) { DruidDataSource druidDataSource = (DruidDataSource)properties.initializeDataSourceBuilder().type(DruidDataSource.class).build(); DatabaseDriver databaseDriver = DatabaseDriver.fromJdbcUrl(properties.determineUrl()); String validationQuery = databaseDriver.getValidationQuery(); if (validationQuery != null) { druidDataSource.setValidationQuery(validationQuery); } return druidDataSource; } } @Bean public ServletRegistrationBean statViewServlet() { ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); // IP白名单 servletRegistrationBean.addInitParameter("allow", "127.0.0.1,192.168.1.83"); // IP黑名单(优先级高于白名单) servletRegistrationBean.addInitParameter("deny", "192.168.1.100"); // 控制台管理用户 servletRegistrationBean.addInitParameter("loginUsername", "liuy"); servletRegistrationBean.addInitParameter("loginPassword", "123456"); // 是否能够重置数据 servletRegistrationBean.addInitParameter("resetEnable", "false"); return servletRegistrationBean; } @Bean public FilterRegistrationBean statFilter() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter()); // 添加过滤规则 filterRegistrationBean.addUrlPatterns("/*"); // 忽略过滤的格式 filterRegistrationBean.addInitParameter("exclusions", "*.js,*.css,*.jpg,*.ico,/druid/*"); return filterRegistrationBean; } }
application.properties:
spring.profiles.active=dev server.port=9090 ##################################mysql数据源配置################################## spring.datasource.url=jdbc:mysql://localhost/db_test?useUnicode=true&characterEncoding=utf-8 spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver # druid连接池 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource # 初始化大小,最小,最大 spring.datasource.druid.initial-size=5 spring.datasource.druid.minIdle=5 spring.datasource.druid.maxActive=20 # 获取连接等待超时的时间(毫秒) spring.datasource.druid.max-wait=60000 # 间隔多久进行一次检测,检测需要关闭的空闲连接(毫秒) spring.datasource.druid.time-between-eviction-runs-millis=60000 # 一个连接在池中的最小生存时间(毫秒) spring.datasource.druid.min-evictable-idle-time-millis=300000 spring.datasource.druid.validation-query=SELECT 1 FROM DUAL spring.datasource.druid.test-while-idle=true spring.datasource.druid.test-on-borrow=false spring.datasource.druid.test-on-return=false # 打开PSCache,并且指定每个连接上PSCache的大小 spring.datasource.druid.pool-prepared-statements=true spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20 # 查询超时时间 spring.datasource.druid.query-timeout=6000 # 事务查询超时时间 spring.datasource.druid.transaction-query-timeout=6000 # 关闭空闲连接超时时间 spring.datasource.druid.remove-abandoned-timeout=1800 # sql监控配置:filter类名:stat,config,encoding,logging spring.datasource.druid.filters=stat # 通过connect-properties属性来打开mergesql功能;慢查询记录 spring.datasource.druid.connect-properties.druid.stat.meergeSql=true; spring.datasource.druid.connect-properties.druid.stat.slowSqlMillis=5000 # 合并多个druidDataSource的监控数据 #spring.datasource.druid.use-global-data-source-stat=true ##################################mybatis基于xml集成################################## #扫包 mybatis.mapper-locations: classpath:mybatis/*.xml #别名 mybatis.type-aliases-package: com.liuy.demo.pojo