最新版本jdbcutils集成log4j做详细sql日志、自动释放连接...等

在这里插入图片描述

maven坐标

      <!-- MySQL 8 --><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><version>8.0.33</version></dependency><!-- Druid连接池 --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.16</version></dependency><!-- Jackson用于JSON处理 --><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.15.2</version></dependency><!-- Log4j2日志 --><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-api</artifactId><version>2.20.0</version></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-core</artifactId><version>2.20.0</version></dependency>
import com.alibaba.druid.pool.DruidDataSource;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;import java.sql.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;public class JDBCUtils {private static DruidDataSource dataSource = null;private static ThreadLocal<ConnectionWrapper> connectionThreadLocal = new ThreadLocal<>();private static final Logger logger = LogManager.getLogger(JDBCUtils.class);private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);private static final ObjectMapper objectMapper = new ObjectMapper();private static final Pattern paramPattern = Pattern.compile("\\?");private static final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");private static void initializeDataSource() {if (dataSource == null) {synchronized (JDBCUtils.class) {if (dataSource == null) {dataSource = new DruidDataSource();dataSource.setUrl("jdbc:mysql://localhost:3306/hello-travel");dataSource.setUsername("root");dataSource.setPassword("root");dataSource.setInitialSize(5);dataSource.setMinIdle(5);dataSource.setMaxActive(20);try {dataSource.setFilters("stat");logger.info("Database connection pool initialized at {}",LocalDateTime.now().format(dateFormatter));} catch (SQLException e) {logger.error("Initialize Druid connection pool failed at {}",LocalDateTime.now().format(dateFormatter), e);throw new RuntimeException(e);}}}}}public static Connection getConnection() {ConnectionWrapper wrapper = connectionThreadLocal.get();if (wrapper == null || wrapper.isExpired()) {if (dataSource == null) {initializeDataSource();}try {Connection conn = dataSource.getConnection();wrapper = new ConnectionWrapper(conn);connectionThreadLocal.set(wrapper);scheduleConnectionRelease(wrapper);logger.debug("New database connection created at {}",LocalDateTime.now().format(dateFormatter));} catch (SQLException e) {logger.error("Get database connection failed at {}",LocalDateTime.now().format(dateFormatter), e);throw new RuntimeException("Get database connection failed", e);}}wrapper.renew();return wrapper.getConnection();}private static void scheduleConnectionRelease(ConnectionWrapper wrapper) {scheduler.schedule(() -> {if (wrapper.isExpired()) {closeConnection();logger.debug("Expired connection closed at {}",LocalDateTime.now().format(dateFormatter));}}, 5, TimeUnit.SECONDS);}public static void closeConnection() {ConnectionWrapper wrapper = connectionThreadLocal.get();if (wrapper != null) {try {wrapper.getConnection().close();logger.debug("Database connection closed at {}",LocalDateTime.now().format(dateFormatter));} catch (SQLException e) {logger.error("Close database connection failed at {}",LocalDateTime.now().format(dateFormatter), e);} finally {connectionThreadLocal.remove();}}}public static Object execute(String sql, Object... params) throws SQLException {// Record start timeLocalDateTime startTime = LocalDateTime.now();String formattedStartTime = startTime.format(dateFormatter);Connection connection = getConnection();ObjectNode logEntry = objectMapper.createObjectNode();logEntry.put("prePareStatementSql", sql);logEntry.put("startTime", formattedStartTime);// Create parameter mappingMap<String, Object> paramMap = createParamMap(sql, params);logEntry.set("params", objectMapper.valueToTree(paramMap));try (PreparedStatement stmt = connection.prepareStatement(sql)) {// Set parametersfor (int i = 0; i < params.length; i++) {stmt.setObject(i + 1, params[i]);}boolean isQuery = sql.trim().toLowerCase().startsWith("select");String actualSql = replaceSqlParams(sql, params);if (isQuery) {try (ResultSet rs = stmt.executeQuery()) {ArrayNode results = objectMapper.createArrayNode();ResultSetMetaData metaData = rs.getMetaData();int columnCount = metaData.getColumnCount();while (rs.next()) {ObjectNode row = objectMapper.createObjectNode();for (int i = 1; i <= columnCount; i++) {String columnName = metaData.getColumnLabel(i);Object value = rs.getObject(i);if (value != null) {row.putPOJO(columnName, value);} else {row.putNull(columnName);}}results.add(row);}// Log execution infoLocalDateTime endTime = LocalDateTime.now();String formattedEndTime = endTime.format(dateFormatter);long executionTimeMs = java.time.Duration.between(startTime, endTime).toMillis();logEntry.put("type", "query");logEntry.put("resultCount", results.size());logEntry.put("actualSql", actualSql);logEntry.put("endTime", formattedEndTime);logEntry.put("executionTimeMs", executionTimeMs);logger.info("SQL Execution Log: {}", logEntry.toString());return results;}} else {int affected = stmt.executeUpdate();// Log execution infoLocalDateTime endTime = LocalDateTime.now();String formattedEndTime = endTime.format(dateFormatter);long executionTimeMs = java.time.Duration.between(startTime, endTime).toMillis();ObjectNode result = objectMapper.createObjectNode();result.put("affectedRows", affected);logEntry.put("type", "update");logEntry.put("affectedRows", affected);logEntry.put("actualSql", actualSql);logEntry.put("endTime", formattedEndTime);logEntry.put("executionTimeMs", executionTimeMs);logger.info("SQL Execution Log: {}", logEntry.toString());return result;}} catch (SQLException e) {// Log error infoLocalDateTime endTime = LocalDateTime.now();String formattedEndTime = endTime.format(dateFormatter);long executionTimeMs = java.time.Duration.between(startTime, endTime).toMillis();logEntry.put("error", e.getMessage());logEntry.put("endTime", formattedEndTime);logEntry.put("executionTimeMs", executionTimeMs);logger.error("SQL Execution Log: {}", logEntry.toString());throw e;}
}private static Map<String, Object> createParamMap(String sql, Object[] params) {Map<String, Object> paramMap = new LinkedHashMap<>();Matcher matcher = paramPattern.matcher(sql);int paramIndex = 0;while (matcher.find() && paramIndex < params.length) {// 获取?前后的上下文int start = Math.max(0, matcher.start() - 20);int end = Math.min(sql.length(), matcher.end() + 20);String context = sql.substring(start, end);// 尝试提取参数名String paramName = extractParamName(context);String key = paramName != null ?String.format("%s (param%d)", paramName, paramIndex + 1) :String.format("param%d", paramIndex + 1);Object value = params[paramIndex];paramMap.put(key, value != null ? value : "null");paramIndex++;}return paramMap;}private static String extractParamName(String context) {Pattern pattern = Pattern.compile("(WHERE|AND|OR|SET|INSERT|UPDATE|DELETE)\\s+([\\w_]+)\\s*=\\s*\\?",Pattern.CASE_INSENSITIVE);Matcher matcher = pattern.matcher(context);if (matcher.find()) {return matcher.group(2);}return null;}private static String replaceSqlParams(String sql, Object[] params) {StringBuilder result = new StringBuilder(sql);int offset = 0;for (int i = 0; i < params.length; i++) {int questionMarkIndex = result.indexOf("?", offset);if (questionMarkIndex == -1) break;String paramValue = params[i] == null ? "NULL" :params[i] instanceof String || params[i] instanceof Date ?"'" + params[i] + "'" : params[i].toString();result.replace(questionMarkIndex, questionMarkIndex + 1, paramValue);offset = questionMarkIndex + paramValue.length();}return result.toString();}public static void shutdown() {logger.info("Initiating JDBCUtils shutdown at {}",LocalDateTime.now().format(dateFormatter));scheduler.shutdownNow();try {if (!scheduler.awaitTermination(5, TimeUnit.SECONDS)) {logger.warn("Scheduler did not terminate within 5 seconds at {}",LocalDateTime.now().format(dateFormatter));}} catch (InterruptedException e) {Thread.currentThread().interrupt();logger.error("Shutdown interrupted at {}",LocalDateTime.now().format(dateFormatter), e);}if (dataSource != null) {dataSource.close();logger.info("Database connection pool closed at {}",LocalDateTime.now().format(dateFormatter));}}private static class ConnectionWrapper {private final Connection connection;private long lastAccessTime;private static final long TIMEOUT = 5000; // 5 seconds timeoutpublic ConnectionWrapper(Connection connection) {this.connection = connection;this.lastAccessTime = System.currentTimeMillis();}public Connection getConnection() {return connection;}public void renew() {this.lastAccessTime = System.currentTimeMillis();}public boolean isExpired() {return System.currentTimeMillis() - lastAccessTime > TIMEOUT;}}
}

resource目录的log4j2.xml文件内容

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN"><Properties><!-- 定义日志格式,添加颜色支持 --><Property name="LOG_PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %highlight{%-5level}{ERROR=red, WARN=yellow, INFO=green} %logger{36} - %msg%n</Property></Properties><Appenders><!-- 控制台输出 --><Console name="Console" target="SYSTEM_OUT"><PatternLayout pattern="${LOG_PATTERN}"/></Console></Appenders><Loggers><!-- 根日志记录器配置 --><Root level="INFO"><AppenderRef ref="Console"/></Root></Loggers>
</Configuration>

在这里插入图片描述
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/456856.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

软考中级嵌入式系统设计师笔记分享(二)

1.TTL 电路是电流控制器件&#xff0c;而CMOS 电路是电压控制器件。 2.TTL 电路的速度快&#xff0c;传输延迟时间短(5-10ns)&#xff0c;但是功耗大。 常见的串行总线有 SPI、II2C、USB、RS232/RS422/RS485、CAN等;高速串行总线主要有 SATA、PCIE、IEEE 1394、Rapidl0、USB 3…

C# Unity 同步/异步编程和多线程什么关系?async/await和coroutine又是什么?

目录 不用模板生成的目录怎么这么丑啊 1.同步&#xff1f;异步&#xff1f;多线程&#xff1f; 2.async/await和coroutine&#xff1f; 证明 单线程中的同步/异步 同 异 多线程中的同步异步 同 异 1.同步&#xff1f;异步&#xff1f;多线程&#xff1f; 首先&#…

模型选择拟合

1.通过多项式拟合交互探索概念 import math import numpy as np import torch from torch import nn from d2l import torch as d2l 2.使用三阶多项式来生成训练和测试数据的标签 max_degree 20 # 多项式的最大阶数 n_train, n_test 100, 100 # 训练和测试数据集大小 true…

手动改造UPX壳,增加IAT保护

随便拿Delphi7&#xff0c;新建一个VCL窗体程序&#xff0c;画一个按钮&#xff0c;写两行代码。这一步骤讲究的是什么呢&#xff1f;率性而为&#xff0c;反正没什么卵用。比如&#xff0c;俺写的是这玩意。 <span style"color:#666666"><span style"…

FFMPEG+Qt 实时显示本机USB摄像头1080p画面以及同步录制mp4视频

FFMPEGQt 实时显示本机USB摄像头1080p画面以及同步录制mp4视频 文章目录 FFMPEGQt 实时显示本机USB摄像头1080p画面以及同步录制mp4视频1、前言1.1 目标1.2 一些说明 2、效果3、代码3.1 思路3.2 工程目录3.3 核心代码 4、全部代码获取 1、前言 本文通过FFMPEG(7.0.2)与Qt(5.13.…

YOLO系列入门:1、YOLO V11环境搭建

YOLO了解 yolo检测原理 yolo是目标检测模型&#xff0c;目标检测包含物体分类、位置预测两个内容。目前yolo的开发公司官网为&#xff1a;https://docs.ultralytics.com/zh截止到目前2024年10月&#xff0c;最新的是yolo11。关于YOLO的介绍可以参考这篇文章&#xff1a;https…

Python+Django+VUE 搭建深度学习训练界面 (持续ing)

PythonDjangoVUE 搭建深度学习训练界面 &#xff08;持续ing&#xff09; 环境说明 Pycharm 专业版2024.1.4&#xff0c;社区版不支持网页开发 下载链接&#xff1a;https://www.jetbrains.com/pycharm/download/other.html 参考链接&#xff1a;https://www.quanxiaoha.co…

es实现桶聚合

目录 聚合 聚合的分类 DSL实现桶聚合 dsl语句 结果 聚合结果排序 限定聚合范围 总结 聚合必须的三要素&#xff1a; 聚合可配置的属性 DSL实现metric聚合 例如&#xff1a;我们需要获取每个品牌的用户评分的min,max,avg等值 只求socre的max 利用RestHighLevelClien…

BIO,NIO,直接内存,零拷贝

前置知识 什么是Socket&#xff1f; Socket是应用层与TCP/IP协议族通信的中间软件抽象层&#xff0c;它是一组接口&#xff0c;一般由操作系统提供。在设计模式中&#xff0c;Socket其实就是一个门面模式&#xff0c;它把复杂的TCP/IP协议处理和通信缓存管理等等都隐藏在Sock…

vue3使用i18n做国际化多语言,实现常量跟随语言切换翻译

因为我有一个常量的配置文件在项目中&#xff0c;而且有中文内容&#xff0c;我想在切换语言的时候&#xff0c;跟着这个翻译也实时切换&#xff0c;就可以使用computed计算属性实现。 把name改成下面的样子&#xff1a; name: computed(() > t(pad.regularMode)), 就可以…

分享一款录屏、直播软件

光音录屏 光音录屏 是新一代的录屏工具&#xff0c;跟传统录屏工具相比&#xff0c;它不仅可以录制屏幕&#xff0c;还可以同时录制「人像 屏幕」&#xff0c;此外它还提供了美颜、虚拟背景、绿幕抠像、图片、文本编辑、字幕、白板等更多高级功能。你可以将录制好的视频&…

ue5实现数字滚动增长

方法1 https://www.bilibili.com/video/BV1h14y197D1/?spm_id_from333.999.0.0 b站教程 重写loop节点 方法二 写在eventtick里

ffmpeg视频滤镜: 色温- colortemperature

滤镜简述 colortemperature 官网链接 》 FFmpeg Filters Documentation 这个滤镜可以调节图片的色温&#xff0c;色温值越大显得越冷&#xff0c;可以参考一下下图&#xff1a; 咱们装修的时候可能会用到&#xff0c;比如选择灯还有地板的颜色的时候&#xff0c;选暖色调还是…

多厂商的实现不同vlan间通信

Cisco单臂路由 Cisco路由器配置 -交换机配置 -pc配置 华三的单臂路由 -路由器配置 -华三的接口默认是打开的 -pc配置及ping的结果 -注意不要忘记配置默认网关 Cisco-SVI -交换机的配置 -创建vlan -> 设置物理接口对应的Acess或Trunk -> 进入vlan接口&#xff0c;打开接…

【纯血鸿蒙】HarmonyOS和OpenHarmony 的区别

一、开源鸿蒙&#xff08;Open Harmony&#xff09; 鸿蒙系统愿来的设计初衷&#xff0c;就是让所有设备都可以运行一个系统&#xff0c;但是每个设备的运算能力和功能都不同&#xff0c;所以内核的设计上&#xff0c;采用了微内核的设计&#xff0c;除了最基础的功能放在内核…

mfc之tab标签控件的使用--附TabSheet源码

TabSheet源码 TabSheet.h #if !defined(AFX_TABSHEET_H__42EE262D_D15F_46D5_8F26_28FD049E99F4__INCLUDED_) #define AFX_TABSHEET_H__42EE262D_D15F_46D5_8F26_28FD049E99F4__INCLUDED_#if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // TabSheet.h : …

C++面向对象编程学习

C面向对象编程学习 前言一、C面向对象编程二、知识点学习1. 定义一个类1.1 使用struct定义1.2 使用class定义1.3 struct和class的区别 2. 类的定义方式2.1 单文件定义&#xff08;Inline Definition&#xff09;2.2 分离定义&#xff08;Separate Definition&#xff09;2.3 头…

[bug] vllm 0.6.1 RuntimeError: operator torchvision::nms does not exist

[bug] vllm 0.6.1 RuntimeError: operator torchvision::nms does not exist 环境 python 3.10 torch 2.4.0cu118 torchvision 0.19.0cu118 vllm 0.6.1.post2cu118问题详情 if torch._C._d…

【华为路由】OSPF多区域配置

网络拓扑 设备接口地址 设备 端口 IP地址 RTA Loopback 0 1.1.1.1/32 G0/0/0 10.1.1.1/24 RTB Loopback 0 2.2.2.2/32 G0/0/0 10.1.1.2/24 G0/0/1 10.1.2.1/24 RTC Loopback 0 3.3.3.3/32 G0/0/0 10.1.2.2/24 G0/0/1 10.1.3.1/24 RTD Loopback 0 4.4.4…

【Jenkins】解决在Jenkins Agent节点容器内无法访问物理机的docker和docker compose的问题

解决在Jenkins Agent节点容器内无法访问物理机的docker和docker compose的问题 1. 确定物理机docker和docker compose已经安装2. 编写Jenkins Agent结点docker-compose.yaml配置文件3. 修改docker运行时文件权限4. 启动容器并验证 最近接触到一个发布产物是一个 docker镜像的项…