spring boot配置druid鏈接池鏈接mysql

概述

spring boot如今的默認鏈接池是Hikari,號稱是性能最好的鏈接池,不過國內使用較多的是阿里開源的druid鏈接池,在阿里的諸多項目中通過實踐驗證,本文介紹怎樣在spring boot中集成druidhtml

準備數據

咱們會使用與教程spring boot 鏈接 mysql一樣的數據,如無數據請參照該教程準備數據,該教程詳細介紹了經過mysql圖形客戶端workbench生成數據的過程。若是傾向使用mysql命令行客戶端,下面是建立數據庫和插入數據的sql語句。java

sql語句

mysql命令行客戶端鏈接數據庫:mysql

mysql -h localhost -u root -p

建立數據庫git

CREATE DATABASE qikegu_demo CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

建立表的sql語句:github

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語句:web

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

image

添加druid依賴

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

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

完整的pom.xml文件內容以下:shell

<?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配置文件:

image

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

image

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接口)例子),使用瀏覽器訪問,輸出從數據庫中讀取的用戶手機號

image

使用druid的監控功能

druid的監控功能,能夠經過網址:http://localhost:8096/druid/index.html 查看。 查看DataSource頁面,能夠看到咱們的配置確實生效了:

image

總結

本文介紹了怎樣在spring boot項目中集成druid鏈接池,使用JdbcTemplate訪問數據庫,驗證數據庫鏈接成功。

完整代碼

相關文章
相關標籤/搜索