SpringBoot整合Druid實現(xiàn)數(shù)據(jù)庫連接池和監(jiān)控
1、Druid的簡介
Druid是Java語言中使用的比較多的數(shù)據(jù)庫連接池。Druid還提供了強大的監(jiān)控和擴展功能。下面將介紹SpringBoot整合Druid實現(xiàn)數(shù)據(jù)庫連接池和監(jiān)控功能。
官方文檔:《Druid官方文檔》
2、創(chuàng)建SpringBoot項目與數(shù)據(jù)表
【實例】SpringBoot整合Druid實現(xiàn)數(shù)據(jù)庫連接池和監(jiān)控,使用MyBaits操作數(shù)據(jù)庫,獲取用戶信息,如下圖:
2.1 創(chuàng)建項目
(1)創(chuàng)建SpringBoot項目,項目結(jié)構(gòu)如下圖:
(2)使用Maven添加依賴文件
在pom.xml配置信息文件中,添加Druid連接池、MyBatis、MySQL數(shù)據(jù)庫、Thymeleaf模板引擎等相關(guān)依賴:
<!-- 引入Druid連接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.23</version> </dependency> <!-- MyBatis與SpringBoot整合依賴 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency> <!-- MySQL的JDBC數(shù)據(jù)庫驅(qū)動 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.20</version> </dependency> <!-- 引入Thymeleaf模板引擎 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
2.2 創(chuàng)建數(shù)據(jù)表
使用MySQL數(shù)據(jù)庫,創(chuàng)建 tb_user 用戶信息表,并添加數(shù)據(jù)。
-- 判斷數(shù)據(jù)表是否存在,存在則刪除 DROP TABLE IF EXISTS tb_user; -- 創(chuàng)建“用戶信息”數(shù)據(jù)表 CREATE TABLE IF NOT EXISTS tb_user ( user_id INT AUTO_INCREMENT PRIMARY KEY COMMENT '用戶編號', user_name VARCHAR(50) NOT NULL COMMENT '用戶姓名', age INT DEFAULT(0) NOT NULL COMMENT '年齡', blog_url VARCHAR(50) NOT NULL COMMENT '博客地址', blog_remark VARCHAR(50) COMMENT '博客信息' ) COMMENT = '用戶信息表'; -- 添加數(shù)據(jù) INSERT INTO tb_user(user_name,age,blog_url,blog_remark) VALUES('pan_junbiao的博客',32,'https://blog.csdn.net/pan_junbiao','您好,歡迎訪問 pan_junbiao的博客');
3、Druid實現(xiàn)數(shù)據(jù)庫連接池
3.1 Druid的配置
在 application.yml 配置文件中配置Druid數(shù)據(jù)庫連接池和監(jiān)控、MyBatis配置。
#Spring配置 spring: #使用Thymeleaf模板引擎 thymeleaf: mode: HTML5 encoding: UTF-8 cache: false #使用Thymeleaf模板引擎,關(guān)閉緩存 servlet: content-type: text/html #JDBC配置 datasource: url: jdbc:mysql://localhost:3306/db_admin?useSSL=false& username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource #Druid連接池配置 druid: initial-size: 5 #初始化時建立物理連接的個數(shù) max-active: 30 #最大連接池數(shù)量 min-idle: 5 # 最小連接池數(shù)量 druid.max-wait: 60000 #獲取連接時最大等待時間,單位毫秒 time-between-eviction-runs-millis: 60000 #配置間隔多久才進(jìn)行一次檢測,檢測需要關(guān)閉的空閑連接,單位是毫秒 min-evictable-idle-time-millis: 300000 #連接保持空閑而不被驅(qū)逐的最小時間 validation-query: select 'x' #用來檢測連接是否有效的sql 必須是一個查詢語句:mysql中為 select 'x' oracle中為 select 1 from dual test-while-idle: true #建議配置為true,不影響性能,并且保證安全性。申請連接的時候檢測,如果空閑時間大于timeBetweenEvictionRunsMillis,執(zhí)行validationQuery檢測連接是否有效。 test-on-borrow: false #申請連接時會執(zhí)行validationQuery檢測連接是否有效,開啟會降低性能,默認(rèn)為true test-on-return: false #歸還連接時會執(zhí)行validationQuery檢測連接是否有效,開啟會降低性能,默認(rèn)為true pool-prepared-statements: true #是否緩存preparedStatement,mysql5.5+建議開啟 max-pool-prepared-statement-per-connection-size: 50 #要啟用PSCache,必須配置大于0,當(dāng)大于0時,poolPreparedStatements自動觸發(fā)修改為true。 filters: stat,wall #配置監(jiān)控統(tǒng)計攔截的filters,去掉后監(jiān)控界面sql無法統(tǒng)計 connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500 #通過connectProperties屬性來打開mergeSql功能;慢SQL記錄 use-global-data-source-stat: true #合并多個DruidDataSource的監(jiān)控數(shù)據(jù) #StatViewServlet配置 stat-view-servlet.enabled: true #是否啟用StatViewServlet(監(jiān)控頁面)默認(rèn)值為false stat-view-servlet.login-username: admin #設(shè)置訪問druid監(jiān)控頁的賬號,默認(rèn)沒有 stat-view-servlet.login-password: admin #設(shè)置訪問druid監(jiān)控頁的密碼,默認(rèn)沒有 #MyBatis配置 mybatis: type-aliases-package: com.pjb.entity #別名定義 configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #指定 MyBatis 所用日志的具體實現(xiàn),未指定時將自動查找 map-underscore-to-camel-case: true #開啟自動駝峰命名規(guī)則(camel case)映射 lazy-loading-enabled: true #開啟延時加載開關(guān) aggressive-lazy-loading: false #將積極加載改為消極加載(即按需加載),默認(rèn)值就是false #lazy-load-trigger-methods: "" #阻擋不相干的操作觸發(fā),實現(xiàn)懶加載 cache-enabled: true #打開全局緩存開關(guān)(二級環(huán)境),默認(rèn)值就是true
注意:druid的配置節(jié)點是在datasource節(jié)點之下的,節(jié)點的層級關(guān)系不要寫錯了。
3.2 創(chuàng)建實體類(Entity層)
在com.pjb.entity包中,創(chuàng)建UserInfo類(用戶信息實體類)。
package com.pjb.entity; import java.io.Serializable; /** * 用戶信息實體類 * @author pan_junbiao **/ public class UserInfo { private int userId; //用戶編號 private String userName; //用戶姓名 private int age; //年齡 private String blogUrl; //博客地址 private String blogRemark; //博客信息 //省略getter與setter方法... }
3.3 數(shù)據(jù)庫映射層(Mapper層)
在com.pjb.mapper包中,創(chuàng)建UserMapper接口(用戶信息Mapper動態(tài)代理接口)。
package com.pjb.service; import com.pjb.entity.UserInfo; /** * 用戶信息業(yè)務(wù)邏輯接口 * @author pan_junbiao **/ public interface UserService { /** * 根據(jù)用戶ID,獲取用戶信息 */ public UserInfo getUserById(int userId); /** * 新增用戶,并獲取自增主鍵 */ public UserInfo insertUser(UserInfo userInfo); /** * 修改用戶 */ public UserInfo updateUser(UserInfo userInfo); /** * 刪除用戶 */ public int deleteUser(int userId); }
3.4 業(yè)務(wù)邏輯層(Service層)
在com.pjb.service包下,創(chuàng)建UserService接口(用戶信息業(yè)務(wù)邏輯接口)。
package com.pjb.service; import com.pjb.entity.UserInfo; /** * 用戶信息業(yè)務(wù)邏輯接口 * @author pan_junbiao **/ public interface UserService { /** * 根據(jù)用戶ID,獲取用戶信息 */ public UserInfo getUserById(int userId); /** * 新增用戶,并獲取自增主鍵 */ public UserInfo insertUser(UserInfo userInfo); /** * 修改用戶 */ public UserInfo updateUser(UserInfo userInfo); /** * 刪除用戶 */ public int deleteUser(int userId); }
在com.pjb.service.impl包下,創(chuàng)建UserServiceImpl類(用戶信息業(yè)務(wù)邏輯類)。
package com.pjb.service.impl; import com.pjb.entity.UserInfo; import com.pjb.mapper.UserMapper; import com.pjb.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * 用戶信息業(yè)務(wù)邏輯類 * @author pan_junbiao **/ @Service @Transactional public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; /** * 根據(jù)用戶ID,獲取用戶信息 */ @Override public UserInfo getUserById(int userId) { return userMapper.getUserById(userId); } /** * 新增用戶,并獲取自增主鍵 */ @Override public UserInfo insertUser(UserInfo userInfo) { userMapper.insertUser(userInfo); return userInfo; } /** * 修改用戶 */ @Override public UserInfo updateUser(UserInfo userInfo) { userMapper.updateUser(userInfo); return userInfo; } /** * 刪除用戶 */ @Override public int deleteUser(int userId) { return userMapper.deleteUser(userId); } }
在Service類上加上@Transactional事務(wù)注解,否則將會在控制臺打印以下信息:
3.5 控制器方法(Controller層)
在com.pjb.controller包中,創(chuàng)建UserController類(用戶控制器),實現(xiàn)用戶數(shù)據(jù)的查詢、新增、修改、刪除,并實現(xiàn)數(shù)據(jù)的返回。
package com.pjb.controller; import com.pjb.entity.UserInfo; import com.pjb.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; /** * 用戶信息控制器 * @author pan_junbiao **/ @Controller @RequestMapping("/user") public class UserController { @Autowired private UserService userService; /** * 獲取用戶信息 */ @RequestMapping("getUserById") public ModelAndView getUserById(int userId) { //根據(jù)用戶ID,獲取用戶信息 UserInfo userInfo = userService.getUserById(userId); if(userInfo==null) { userInfo = new UserInfo(); } //返回結(jié)果 ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("userInfo",userInfo); modelAndView.setViewName("/user-info.html"); return modelAndView; } /** * 新增用戶 */ @ResponseBody @RequestMapping("insertUser") public boolean insertUser() { //創(chuàng)建新用戶 UserInfo userInfo = new UserInfo(); userInfo.setUserName("pan_junbiao的博客"); userInfo.setAge(32); userInfo.setBlogUrl("https://blog.csdn.net/pan_junbiao"); userInfo.setBlogRemark("您好,歡迎訪問 pan_junbiao的博客"); //執(zhí)行新增方法 userService.insertUser(userInfo); //返回結(jié)果 return userInfo.getUserId() > 0 ? true : false; } /** * 修改用戶 */ @ResponseBody @RequestMapping("updateUser") public boolean updateUser(int userId) { UserInfo userInfo = new UserInfo(); userInfo.setUserId(userId); userInfo.setUserName("pan_junbiao的博客_02"); userInfo.setAge(35); userInfo.setBlogUrl("https://blog.csdn.net/pan_junbiao"); userInfo.setBlogRemark("您好,歡迎訪問 pan_junbiao的博客"); //執(zhí)行修改方法 userService.updateUser(userInfo); //返回結(jié)果 return true; } /** * 刪除用戶 */ @ResponseBody @RequestMapping("deleteUser") public boolean deleteUser(int userId) { //執(zhí)行新增方法 int result = userService.deleteUser(userId); //返回結(jié)果 return result > 0 ? true : false; } }
3.6 顯示頁面(View層)
在 resources/templates 目錄下,創(chuàng)建 user-info.html 用戶信息顯示頁面。
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>用戶信息</title> <meta name="author" content="pan_junbiao的博客"> <style> table { border-collapse: collapse; margin-bottom: 10px} table,table tr th, table tr td { border:1px solid #000000; padding: 5px 10px;} </style> </head> <body> <div align="center"> <table> <caption>用戶信息</caption> <tr> <th>用戶ID:</th> <td th:text="${userInfo.userId}"></td> </tr> <tr> <th>用戶名稱:</th> <td th:text="${userInfo.userName}"></td> </tr> <tr> <th>年齡:</th> <td th:text="${userInfo.age}"></td> </tr> <tr> <th>博客地址:</th> <td th:text="${userInfo.blogUrl}"></td> </tr> <tr> <th>備注信息:</th> <td th:text="${userInfo.blogRemark}"></td> </tr> </table> </div> </body> </html>
執(zhí)行結(jié)果:
(1)使用Druid數(shù)據(jù)庫連接池從數(shù)據(jù)表中,獲取用戶信息,如下圖:
(2)控制臺輸出的信息,如下圖:
4、Druid實現(xiàn)監(jiān)控功能
Druid實現(xiàn)監(jiān)控功能,主要是在配置中,包括配置是否啟動監(jiān)控頁面、設(shè)置訪問監(jiān)控頁面的登錄賬號、密碼等。如下圖:
配置完成后,啟動項目,在瀏覽器中直接輸入如下地址:
http://127.0.0.1:8080/druid/login.html
http://127.0.0.1:8080/druid/index.html
登錄頁面:
Druid監(jiān)控首頁:
源代碼下載:https://github.com/kevinpanjunbiao/DruidDemo
到此這篇關(guān)于SpringBoot整合Druid實現(xiàn)數(shù)據(jù)庫連接池和監(jiān)控的文章就介紹到這了,更多相關(guān)SpringBoot Druid數(shù)據(jù)庫連接池和監(jiān)控內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot中Druid連接池與多數(shù)據(jù)源切換的方法
- SpringBoot整合mybatis使用Druid做連接池的方式
- Springboot中加入druid連接池
- springboot2.0配置連接池(hikari、druid)的方法
- springboot項目整合druid數(shù)據(jù)庫連接池的實現(xiàn)
- springboot集成druid連接池配置的方法
- springboot整合druid連接池的步驟
- SpringBoot使用 druid 連接池來優(yōu)化分頁語句
- SpringBoot整合Druid數(shù)據(jù)庫連接池的方法
- 解決Spring Boot中Druid連接池“discard long time none received connection“警告
相關(guān)文章
SpringBoot之logback-spring.xml不生效的解決方法
這篇文章主要介紹了SpringBoot之logback-spring.xml不生效的解決方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-01-01SpringBoot項目啟動后立馬自動關(guān)閉的解決方案
這篇文章主要介紹了SpringBoot項目啟動后立馬自動關(guān)閉的解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03Spring security如何重寫Filter實現(xiàn)json登錄
這篇文章主要介紹了Spring security 如何重寫Filter實現(xiàn)json登錄,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09SpringMVC @RequestBody Date類型的Json轉(zhuǎn)換方式
這篇文章主要介紹了SpringMVC @RequestBody Date類型的Json轉(zhuǎn)換方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10Java VisualVM監(jiān)控遠(yuǎn)程JVM(詳解)
下面小編就為大家?guī)硪黄狫ava VisualVM監(jiān)控遠(yuǎn)程JVM(詳解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10