目录
一、依赖管理
<!-- druid依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
二、配置druid属性文件
application.yml
#druid
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: 123456
# 初始化大小,最小,最大
initialSize: 5
minIdle: 5
maxActive: 20
# 配置获取连接等待超时的时间(毫秒)
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置有一个连接在连接池中的最小生存时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打开PSCache,指定每个连接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的filters,去掉后监控界面sql将无法统计,'wall'用于防火墙
filters: stat, wall, log4j
# 通过connectProperties属性来打开mergeSql功能,慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
loginUsername: druid
loginPassword: druid
allow:
deny:
三、使用Bean注入配置文件属性
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
public class DruidProps {
private String type;
private String driverClassName;
private String url;
private String username;
private String password;
private int initialSize;
private int minIdle;
private int maxActive;
private int maxWait;
private int timeBetweenEvictionRunsMillis;
private int minEvictableIdleTimeMillis;
private String validationQuery;
private boolean testWhileIdle;
private boolean testOnBorrow;
private boolean testOnReturn;
private boolean poolPreparedStatements;
private int maxPoolPreparedStatementPerConnectionSize;
private String filters;
private String connectionProperties;
private String allow;
private String deny;
private String loginUsername;
private String loginPassword;
}
四、springboot集成druid配置类
DruidConfig.java
import com.alibaba.druid.pool.DruidDataSource;
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.beans.factory.annotation.Autowired;
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 javax.sql.DataSource;
import java.sql.SQLException;
@Configuration
public class DruidConfig {
private static final Logger logger = LoggerFactory.getLogger(DruidConfig.class);
@Autowired
private DruidProps properties;
public DataSource dataSource() throws SQLException {
String url = properties.getUrl();
logger.info("===> DataSource Connection Url {}", url.substring(13, url.indexOf("?")));
DruidDataSource datasource = new DruidDataSource();
datasource.setDriverClassName(properties.getDriverClassName());
datasource.setUrl(url);
datasource.setUsername(properties.getUsername());
datasource.setPassword(properties.getPassword());
datasource.setFilters(properties.getFilters());
datasource.setConnectionProperties(properties.getConnectionProperties());
datasource.setInitialSize(properties.getInitialSize());
datasource.setMinIdle(properties.getMinIdle());
datasource.setMaxActive(properties.getMaxActive());
datasource.setMaxWait(properties.getMaxWait());
datasource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis());
datasource.setMinEvictableIdleTimeMillis(properties.getMinEvictableIdleTimeMillis());
datasource.setValidationQuery(properties.getValidationQuery());
datasource.setTestWhileIdle(properties.isTestWhileIdle());
datasource.setTestOnBorrow(properties.isTestOnBorrow());
datasource.setTestOnReturn(properties.isTestOnReturn());
datasource.setPoolPreparedStatements(properties.isPoolPreparedStatements());
datasource.setMaxPoolPreparedStatementPerConnectionSize(properties.getMaxPoolPreparedStatementPerConnectionSize());
return datasource;
}
@Bean
public ServletRegistrationBean druidServlet(){
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
/**
* 白名单:
*/
servletRegistrationBean.addInitParameter("allow", "");
/**
* 黑名单:
* 存在共同时,deny优先于allow
*/
servletRegistrationBean.addInitParameter("deny", "");
servletRegistrationBean.addInitParameter("loginUsername", properties.getLoginUsername());
servletRegistrationBean.addInitParameter("loginPassword", properties.getLoginPassword());
/**
* 是否能够重置数据. 强制为不允许
*/
servletRegistrationBean.addInitParameter("resetEnable", "false");
return servletRegistrationBean;
}
@Bean
public FilterRegistrationBean druidFilter(){
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
filterRegistrationBean.addUrlPatterns("/druid/*");
return filterRegistrationBean;
}
}
五、登陆druid管理界面
注意:使用springboot的druid依赖,才会记录执行的sql信息,项目重写启动后sql监控信息会被清空
访问地址:http://localhost:8081/druid/sql.html
六、加入mybatis依赖
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
七、配置文件中加入mybatis相关属性
加入mybatis属性后及整合完毕,可以直接编写Mapper.xml和Dao层。然后注入Dao使用
application.yml
#mybatis
mybatis:
configuration:
#开启缓存
cache-enabled: true
#延迟加载
lazy-loading-enabled: true
aggressive-lazy-loading: false
#一个查询返回多个结果集
multiple-result-sets-enabled: true
use-column-label: true
use-generated-keys: false
default-executor-type: simple
#超时秒数
default-statement-timeout: 10
#允许嵌套语句中分页
safe-row-bounds-enabled: false
safe-result-handler-enabled: false
#关闭驼峰命令 a_name隐射到aName
map-underscore-to-camel-case: false
local-cache-scope: session
#insert null时不需要jdbcType默认为下面
jdbc-type-for-null: null
lazy-load-trigger-methods: equals,clone,hashCode,toString
mapper-locations: classpath:mybatis/*.xml
type-aliases-package: