spring boot配置druid连接池连接mysql


Spring Boot 集成教程


概述

spring boot现在的默认连接池是Hikari,号称是性能最好的连接池,不过国内使用较多的是阿里开源的druid连接池,在阿里的诸多项目中经过实践验证,本文介绍怎样在spring boot中集成druid

准备数据

我们会使用与教程spring boot 连接 mysql同样的数据,如无数据请参照该教程准备数据,该教程详细介绍了通过mysql图形客户端workbench生成数据的过程。如果倾向使用mysql命令行客户端,下面是创建数据库和插入数据的sql语句。

sql语句

mysql命令行客户端连接数据库:

mysql -h localhost -u root -p

创建数据库

CREATE DATABASE qikegu_demo CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

创建表的sql语句:

CREATE TABLE `qikegu_demo`.`user` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
`nickname` VARCHAR(50) NULL COMMENT '昵称',
`mobile` VARCHAR(20) NULL COMMENT '手机号',
`password` CHAR(60) NULL COMMENT '密码hash值',
`role` VARCHAR(100) NULL DEFAULT 'user' COMMENT '角色,角色名以逗号分隔',
PRIMARY KEY (`id`),
UNIQUE INDEX `mobile_UNIQUE` (`mobile` ASC))
COMMENT = '用户表';

插入数据的sql语句:

INSERT INTO `qikegu_demo`.`user` (`nickname`, `mobile`, `password`) VALUES ('abc1', '13512345678', '123');
INSERT INTO `qikegu_demo`.`user` (`nickname`, `mobile`, `password`) VALUES ('abc2', '13512345677', '123');

创建项目

创建 spring boot项目

打开Eclipse,创建spring boot的spring starter project项目,在配置依赖时,勾选web, jdbc, mysql,如不清楚怎样创建spring boot项目,参照教程: spring boot hello world (restful接口)例子

spring boot配置druid连接池连接mysql

添加druid依赖

在pom.xml文件中,添加druid依赖

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>

完整的pom.xml文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.qikegu</groupId>
<artifactId>druid-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>druid-demo</name>
<description>Demo project for Spring Boot</description> <properties>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

配置数据库

application.properties配置

打开文件:application.properties,该文件在 src -> main -> resources 目录,配置数据库连接:

# 服务器端口
server.port=8096 # 数据库设置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/qikegu_demo?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=你的数据库密码 # druid配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource # druid参数调优(可选)
# 初始化大小,最小,最大
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.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters
spring.datasource.filters=stat
# asyncInit是1.1.4中新增加的配置,如果有initialSize数量较多时,打开会加快应用启动时间
spring.datasource.asyncInit=true

解释请看代码注释。druid必须的配置其实很少,只需配置一行,表明不使用默认的Hikari,而使用druid。

# druid配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

参数调优部分是可选的,这里列出的参数都是druid官网推荐的典型配置。另外还有监控配置,一般使用不用去管它。

DruidConfig.java配置

由于现在Spring Boot不支持druid配置,参数调优部分的配置不会直接生效,需要配置datasource bean,从application.properties中读取值来装配datasource bean,新增DruidConfig.java配置文件:

spring boot配置druid连接池连接mysql

DruidConfig.java代码如下,通过@value注解读取配置文件中的值

package com.qikegu.demo.config;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary; import com.alibaba.druid.pool.DruidDataSource; @Configuration
public class DruidConfig {
private Logger logger = LoggerFactory.getLogger(DruidConfig.class); @Value("${spring.datasource.url}")
private String dbUrl; @Value("${spring.datasource.username}")
private String username; @Value("${spring.datasource.password}")
private String password; @Value("${spring.datasource.driver-class-name}")
private String driverClassName; @Value("${spring.datasource.initial-size}")
private int initialSize; @Value("${spring.datasource.min-idle}")
private int minIdle; @Value("${spring.datasource.max-active}")
private int maxActive; @Value("${spring.datasource.max-wait}")
private int maxWait; @Value("${spring.datasource.time-between-eviction-runs-millis}")
private int timeBetweenEvictionRunsMillis; @Value("${spring.datasource.min-evictable-idle-time-millis}")
private int minEvictableIdleTimeMillis; // @Value("${spring.datasource.validation-query}")
// private String validationQuery; @Value("${spring.datasource.test-while-idle}")
private boolean testWhileIdle; @Value("${spring.datasource.test-on-borrow}")
private boolean testOnBorrow; @Value("${spring.datasource.test-on-return}")
private boolean testOnReturn; @Value("${spring.datasource.pool-prepared-statements}")
private boolean poolPreparedStatements; @Value("${spring.datasource.max-pool-prepared-statement-per-connection-size}")
private int maxPoolPreparedStatementPerConnectionSize; @Value("${spring.datasource.filters}")
private String filters; // @Value("${spring.datasource.connection-properties}")
// private String connectionProperties; @Bean //声明其为Bean实例
@Primary //在同样的DataSource中,首先使用被标注的DataSource
public DataSource dataSource(){
DruidDataSource datasource = new DruidDataSource(); datasource.setUrl(this.dbUrl);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName); //configuration
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);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
try {
datasource.setFilters(filters);
} catch (SQLException e) {
logger.error("druid configuration initialization filter", e);
}
// datasource.setConnectionProperties(connectionProperties); return datasource;
}
}

访问数据库

添加代码验证数据库是否正常连接,添加文件:HelloController.java

spring boot配置druid连接池连接mysql

HelloController.java的代码


package com.qikegu.demo; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; @RestController
public class HelloController { @Autowired
JdbcTemplate jdbcTemplate; @RequestMapping(value="/hello", method=RequestMethod.GET)
public String index() { String sql = "SELECT mobile FROM user WHERE id = ?"; // 通过jdbcTemplate查询数据库
String mobile = (String)jdbcTemplate.queryForObject(
sql, new Object[] { 1 }, String.class); return "Hello " + mobile;
}
}

我们使用spring的JdbcTemplate(这正是我们在前面引入spring jdbc依赖的原因),比使用原始的jdbc接口方便。

运行

项目的右键菜单,选择:run as -> spring boot app 运行程序(不清楚怎么运行可参考: spring boot hello world (restful接口)例子),使用浏览器访问,输出从数据库中读取的用户手机号

spring boot配置druid连接池连接mysql

使用druid的监控功能

druid的监控功能,可以通过网址:http://localhost:8096/druid/index.html 查看。

查看DataSource页面,可以看到我们的配置确实生效了:

spring boot配置druid连接池连接mysql

总结

本文介绍了怎样在spring boot项目中集成druid连接池,使用JdbcTemplate访问数据库,验证数据库连接成功。

完整代码

上一篇:Entity Framework入门教程(18)---EF6中基于代码进行配置方式


下一篇:spring boot 异常(exception)处理