Springboot项目集成Durid数据源和P6Spy以及dbType not support问题

news2024/9/27 23:32:15

        项目开发阶段,mybatis的SQL打印有占位符,调试起来还是有点麻烦,随想整合P6Spy打印可以直接执行的SQL,方便调试,用的Durid连接池。

Springboot项目集成Durid

<dependency>

    <groupId>com.alibaba</groupId>

    <artifactId>druid-spring-boot-starter</artifactId>

    <version>1.2.18</version>

</dependency>

配置文件application.yml

spring:

  datasource:

    driver-class-name: com.mysql.cj.jdbc.Driver

    url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=true

    username: root

    password: 123456

    # 指定数据源为 DruidDataSource,默认值为 HikariDataSource

    type: com.alibaba.druid.pool.DruidDataSource

    druid:

      initial-size: 5

      min-idle: 5

      max-active: 15

      max-wait: 30000

      min-evictable-idle-time-millis: 30000

      time-between-eviction-runs-millis: 30000

      validation-query: SELECT 1 FROM DUAL

      test-while-idle: true

      test-on-borrow: false

      test-on-return: false

      pool-prepared-statements: true

      max-pool-prepared-statement-per-connection-size: 5

      filters: stat,wall

      use-global-data-source-stat: true

      stat-view-servlet:

        enabled: true

        url-pattern: /druid/*

        login-username: admin

        login-password: 111111

      web-stat-filter:

        enabled: true

        url-pattern: /*

        exclusions: /druid/*, *.js, *.jpeg, *.jpg, *.png, *.gif, *.css

      filter:

        stat:

          merge-sql: true

          slow-sql-millis: 3000

          log-slow-sql: true

配置P6Spy,有两种方式,一种是添加依赖jar包,一种是用p6spy-spring-boot-starter。

第一种:

添加依赖:可以添加到dev环境,生产环境不建议使用,有性能损耗。

<dependency>
    <groupId>p6spy</groupId>
    <artifactId>p6spy</artifactId>
    <version>3.9.1</version>
</dependency>

或者只添加到开发环境

<profiles>
    <profile>
        <id>dev</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <profiles.active>dev</profiles.active>
        </properties>
        <dependencies>
            <dependency>
                <groupId>p6spy</groupId>
                <artifactId>p6spy</artifactId>
                <version>3.9.1</version>
            </dependency>
        </dependencies>
    </profile>
</profiles>

修改数据源配置,需要改2个地方,url和driver-class-name

修改前:

修改后:

spring:
  datasource:
    url: jdbc:p6spy:mysql://x.x.x.x:3306/my_test?allowPublicKeyRetrieval=true&useSSL=true&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&useSSL=false
    username: root
    password: 123456
    driver-class-name: com.p6spy.engine.spy.P6SpyDriver

 

添加spy.properties文件,默认会在项目根目录生成一个spy.log文件,把SQL打印到该文件中。

module.log=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory

# 自定义日志打印

logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger

#日志输出到控制台

appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger

# 使用日志系统记录 sql

#appender=com.p6spy.engine.spy.appender.Slf4JLogger

# 设置 p6spy driver 代理

deregisterdrivers=true

# 取消JDBC URL前缀

useprefix=true

# 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.

excludecategories=info,debug,result,batch,resultset

# 日期格式

dateformat=yyyy-MM-dd HH:mm:ss

# 真实JDBC driver , 多个以 逗号 分割 默认为空

#driverlist=org.h2.Driver

driverlist=oracle.jdbc.OracleDriver

# 是否开启慢SQL记录

outagedetection=true

# 慢SQL记录标准 2 秒

outagedetectioninterval=2

集成完成。

spy.properties参考:

mybatis-plus:

#3.2.1以上使用
modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
#3.2.1以下使用或者不配置
#modulelist=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定义日志打印
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
#日志输出到控制台
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
# 使用日志系统记录 sql
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
# 设置 p6spy driver 代理
deregisterdrivers=true
# 取消JDBC URL前缀
useprefix=true
# 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
excludecategories=info,debug,result,commit,resultset
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 实际驱动可多个
#driverlist=org.h2.Driver
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准 2 秒
outagedetectioninterval=2

官网的例子:

#################################################################

# P6Spy Options File                                            #

# See documentation for detailed instructions                   #

# http://p6spy.github.io/p6spy/2.0/configandusage.html          #

#################################################################



#################################################################

# MODULES                                                       #

#                                                               #

# Module list adapts the modular functionality of P6Spy.        #

# Only modules listed are active.                               #

# (default is com.p6spy.engine.logging.P6LogFactory and         #

# com.p6spy.engine.spy.P6SpyFactory)                            #

# Please note that the core module (P6SpyFactory) can't be      #

# deactivated.                                                  #

# Unlike the other properties, activation of the changes on     #

# this one requires reload.                                     #

#################################################################

#modulelist=com.p6spy.engine.spy.P6SpyFactory,com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory



################################################################

# CORE (P6SPY) PROPERTIES                                      #

################################################################



# A comma separated list of JDBC drivers to load and register.

# (default is empty)

#

# Note: This is normally only needed when using P6Spy in an

# application server environment with a JNDI data source or when

# using a JDBC driver that does not implement the JDBC 4.0 API

# (specifically automatic registration).

#driverlist=



# for flushing per statement

# (default is false)

#autoflush=false



# sets the date format using Java's SimpleDateFormat routine.

# In case property is not set, milliseconds since 1.1.1970 (unix time) is used (default is empty)

#dateformat=



# prints a stack trace for every statement logged

#stacktrace=false

# if stacktrace=true, specifies the stack trace to print

#stacktraceclass=



# determines if property file should be reloaded

# Please note: reload means forgetting all the previously set

# settings (even those set during runtime - via JMX)

# and starting with the clean table

# (default is false)

#reloadproperties=false



# determines how often should be reloaded in seconds

# (default is 60)

#reloadpropertiesinterval=60



# specifies the appender to use for logging

# Please note: reload means forgetting all the previously set

# settings (even those set during runtime - via JMX)

# and starting with the clean table

# (only the properties read from the configuration file)

# (default is com.p6spy.engine.spy.appender.FileLogger)

#appender=com.p6spy.engine.spy.appender.Slf4JLogger

#appender=com.p6spy.engine.spy.appender.StdoutLogger

#appender=com.p6spy.engine.spy.appender.FileLogger



# name of logfile to use, note Windows users should make sure to use forward slashes in their pathname (e:/test/spy.log)

# (used for com.p6spy.engine.spy.appender.FileLogger only)

# (default is spy.log)

#logfile=spy.log



# append to the p6spy log file. if this is set to false the

# log file is truncated every time. (file logger only)

# (default is true)

#append=true



# class to use for formatting log messages (default is: com.p6spy.engine.spy.appender.SingleLineFormat)

#logMessageFormat=com.p6spy.engine.spy.appender.SingleLineFormat



# Custom log message format used ONLY IF logMessageFormat is set to com.p6spy.engine.spy.appender.CustomLineFormat

# default is %(currentTime)|%(executionTime)|%(category)|connection%(connectionId)|%(sqlSingleLine)

# Available placeholders are:

#   %(connectionId)            the id of the connection

#   %(currentTime)             the current time expressing in milliseconds

#   %(executionTime)           the time in milliseconds that the operation took to complete

#   %(category)                the category of the operation

#   %(effectiveSql)            the SQL statement as submitted to the driver

#   %(effectiveSqlSingleLine)  the SQL statement as submitted to the driver, with all new lines removed

#   %(sql)                     the SQL statement with all bind variables replaced with actual values

#   %(sqlSingleLine)           the SQL statement with all bind variables replaced with actual values, with all new lines removed

#customLogMessageFormat=%(currentTime)|%(executionTime)|%(category)|connection%(connectionId)|%(sqlSingleLine)



# format that is used for logging of the java.util.Date implementations (has to be compatible with java.text.SimpleDateFormat)

# (default is yyyy-MM-dd'T'HH:mm:ss.SSSZ)

#databaseDialectDateFormat=yyyy-MM-dd'T'HH:mm:ss.SSSZ



# format that is used for logging of the java.sql.Timestamp implementations (has to be compatible with java.text.SimpleDateFormat)

# (default is yyyy-MM-dd'T'HH:mm:ss.SSSZ)

#databaseDialectTimestampFormat=yyyy-MM-dd'T'HH:mm:ss.SSSZ



# format that is used for logging booleans, possible values: boolean, numeric

# (default is boolean)

#databaseDialectBooleanFormat=boolean



# Specifies the format for logging binary data. Not applicable if excludebinary is true.

# (default is com.p6spy.engine.logging.format.HexEncodedBinaryFormat)

#databaseDialectBinaryFormat=com.p6spy.engine.logging.format.PostgreSQLBinaryFormat

#databaseDialectBinaryFormat=com.p6spy.engine.logging.format.MySQLBinaryFormat

#databaseDialectBinaryFormat=com.p6spy.engine.logging.format.HexEncodedBinaryFormat



# whether to expose options via JMX or not

# (default is true)

#jmx=true



# if exposing options via jmx (see option: jmx), what should be the prefix used?

# jmx naming pattern constructed is: com.p6spy(.<jmxPrefix>)?:name=<optionsClassName>

# please note, if there is already such a name in use it would be unregistered first (the last registered wins)

# (default is none)

#jmxPrefix=



# if set to true, the execution time will be measured in nanoseconds as opposed to milliseconds

# (default is false)

#useNanoTime=false



#################################################################

# DataSource replacement                                        #

#                                                               #

# Replace the real DataSource class in your application server  #

# configuration with the name com.p6spy.engine.spy.P6DataSource #

# (that provides also connection pooling and xa support).       #

# then add the JNDI name and class name of the real             #

# DataSource here                                               #

#                                                               #

# Values set in this item cannot be reloaded using the          #

# reloadproperties variable. Once it is loaded, it remains      #

# in memory until the application is restarted.                 #

#                                                               #

#################################################################

#realdatasource=/RealMySqlDS

#realdatasourceclass=com.mysql.jdbc.jdbc2.optional.MysqlDataSource



#################################################################

# DataSource properties                                         #

#                                                               #

# If you are using the DataSource support to intercept calls    #

# to a DataSource that requires properties for proper setup,    #

# define those properties here. Use name value pairs, separate  #

# the name and value with a semicolon, and separate the         #

# pairs with commas.                                            #

#                                                               #

# The example shown here is for mysql                           #

#                                                               #

#################################################################

#realdatasourceproperties=port;3306,serverName;myhost,databaseName;jbossdb,foo;bar



#################################################################

# JNDI DataSource lookup                                        #

#                                                               #

# If you are using the DataSource support outside of an app     #

# server, you will probably need to define the JNDI Context     #

# environment.                                                  #

#                                                               #

# If the P6Spy code will be executing inside an app server then #

# do not use these properties, and the DataSource lookup will   #

# use the naming context defined by the app server.             #

#                                                               #

# The two standard elements of the naming environment are       #

# jndicontextfactory and jndicontextproviderurl. If you need    #

# additional elements, use the jndicontextcustom property.      #

# You can define multiple properties in jndicontextcustom,      #

# in name value pairs. Separate the name and value with a       #

# semicolon, and separate the pairs with commas.                #

#                                                               #

# The example shown here is for a standalone program running on #

# a machine that is also running JBoss, so the JNDI context     #

# is configured for JBoss (3.0.4).                              #

#                                                               #

# (by default all these are empty)                              #

#################################################################

#jndicontextfactory=org.jnp.interfaces.NamingContextFactory

#jndicontextproviderurl=localhost:1099

#jndicontextcustom=java.naming.factory.url.pkgs;org.jboss.naming:org.jnp.interfaces



#jndicontextfactory=com.ibm.websphere.naming.WsnInitialContextFactory

#jndicontextproviderurl=iiop://localhost:900



################################################################

# P6 LOGGING SPECIFIC PROPERTIES                               #

################################################################



# filter what is logged

# please note this is a precondition for usage of: include/exclude/sqlexpression

# (default is false)

#filter=false



# comma separated list of strings to include

# please note that special characters escaping (used in java) has to be done for the provided regular expression

# (default is empty)

#include=

# comma separated list of strings to exclude

# (default is empty)

#exclude=



# sql expression to evaluate if using regex

# please note that special characters escaping (used in java) has to be done for the provided regular expression

# (default is empty)

#sqlexpression=



#list of categories to exclude: error, info, batch, debug, statement,

#commit, rollback, result and resultset are valid values

# (default is info,debug,result,resultset,batch)

#excludecategories=info,debug,result,resultset,batch



#whether the binary values (passed to DB or retrieved ones) should be logged with placeholder: [binary] or not.

# (default is false)

#excludebinary=false



# Execution threshold applies to the standard logging of P6Spy.

# While the standard logging logs out every statement

# regardless of its execution time, this feature puts a time

# condition on that logging. Only statements that have taken

# longer than the time specified (in milliseconds) will be

# logged. This way it is possible to see only statements that

# have exceeded some high water mark.

# This time is reloadable.

#

# executionThreshold=integer time (milliseconds)

# (default is 0)

#executionThreshold=



################################################################

# P6 OUTAGE SPECIFIC PROPERTIES                                #

################################################################

# Outage Detection

#

# This feature detects long-running statements that may be indicative of

# a database outage problem. If this feature is turned on, it will log any

# statement that surpasses the configurable time boundary during its execution.

# When this feature is enabled, no other statements are logged except the long

# running statements. The interval property is the boundary time set in seconds.

# For example, if this is set to 2, then any statement requiring at least 2

# seconds will be logged. Note that the same statement will continue to be logged

# for as long as it executes. So if the interval is set to 2, and the query takes

# 11 seconds, it will be logged 5 times (at the 2, 4, 6, 8, 10 second intervals).

#

# outagedetection=true|false

# outagedetectioninterval=integer time (seconds)

#

# (default is false)

#outagedetection=false

# (default is 60)

#outagedetectioninterval=30

第二种:

添加依赖:

<dependency>
    <groupId>com.github.gavlyukovskiy</groupId>
    <artifactId>p6spy-spring-boot-starter</artifactId>
    <version>1.9.0</version>
</dependency>

修改数据源配置:同第一种方式,修改后

添加配置:这里和第一种方式不一样,可以添加个开关 enabled: true

decorator:

  datasource:

    p6spy:

      logging: file

      log-file: spy.log

      log-format: executionTime:%(executionTime) | sql:%(sqlSingleLine)

集成完成。

spy.log文件,日志格式可以通过配置文件修改,请另行参考网上的资料。

 

可能遇到的问题:dbType not support : null,这是没有识别出dbType,Durid数据源会存在该问题。

 解决方式:修改Durid配置中的filter,在stat和wall指定dbType和enabled

 

总结: 除了dbType not support这个问题外,我这还遇到了connection error的问题,最后发现其实和P6Spy无关。我这不是纯净的框架,数据源配置都是jar包的方式继承的父项目,改起来很费劲。P6Spy配置其实很简单,Durid连接池用MySQL的时候会有dbType不识别问题,其余的数据源都很好集成,如果遇到其余的稀奇古怪的问题,请先排查框架本身是否正常。

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【Matlab】极限学习机遗传算法(ELM-GA)函数极值寻优——非线性函数求极值

往期博客&#x1f449; 【Matlab】BP神经网络遗传算法(BP-GA)函数极值寻优——非线性函数求极值 【Matlab】GRNN神经网络遗传算法(GRNN-GA)函数极值寻优——非线性函数求极值 【Matlab】RBF神经网络遗传算法(RBF-GA)函数极值寻优——非线性函数求极值 【Matlab】Elman神经网络遗…

栈和队列 (以及实现)

文章内容 1.栈 2.队列 文章内容 1.栈 1.1栈的概念及结构 栈&#xff1a;一种特殊的线性表&#xff0c;其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端称为栈顶&#xff0c;另一端称为栈底。栈中的数据元素遵守后进先出LIFO&#xff08;Last I…

软件测试还是测试开发,二者如何选择?

各位小伙伴大家好, 今天和大家分享的是测试和测试开发的选择&#xff0c;相信很多小伙伴在这个问题上也都有过自己的想法&#xff0c;闲言少叙, 咱们进入正题。 一.企业需要哪种人才&#xff1f; 一名优秀的测试工程师是市面上不可多得的人才, 拥有理论和实操能力的测试工程师…

“代言人+合伙人“模式,彻底改变传统的一对一代言活动

小编介绍&#xff1a;10年专注商业模式设计及软件开发&#xff0c;擅长企业生态商业模式&#xff0c;商业零售会员增长裂变模式策划、商业闭环模式设计及方案落地&#xff1b;扶持10余个电商平台做到营收过千万&#xff0c;数百个平台达到百万会员&#xff0c;欢迎咨询。 当今…

MyBatis 实战指南:探索灵活持久化的艺术

文章目录 前言一、初识 MyBatis1.1 什么是 MyBatis1.2 为什么学习 MyBatis 二、MyBatis 在软件开发框架中的定位三、基于 Spring Boot 创建 MyBatis 项目3.1 添加 MyBatis 框架的支持3.2 配置数据库连接信息和映射文件的保存路径&#xff08;Mapper XML&#xff09; 四、MyBati…

8月11日|CSA研讨会:国标要点解读《信息安全技术 个人信息处理中告知和同意实施指南》

随着网络与数据科技的进步&#xff0c;个人信息在AIGC、元宇宙世界等产业中扮演着愈发关键的角色。如何实施告知并取得个人主体同意是个人信息处理的基本前提&#xff0c;对于企业等处理者而言尤为重要。《个人信息保护法》规定了知情同意的原则和一般规则&#xff0c;但仍有不…

网络适配器和MAC地址

点对点信道&#xff1a;由于目的地只有一个选项&#xff0c;所以数据链路层不需要使用地址。 而在广播信道中&#xff1a; 各个主机如何判断信号是不是发给自己的&#xff1f; 当多个主机连接在同一个广播信道上&#xff0c;要想实现两个主机之间的通信&#xff0c;则每个主机都…

字段附加属性

字段附加属性 除了查看、编辑、必填三个基本属性之外,在Html模板中可以对单个字段添加Sql操作,或者进行字段赋值和日期时间计算,这也是Html模板表单的一大特色,如图D5-4-1所示。 D5-4-1 5.5.2、插入sql操作 插入sql操作是通过写sql查询语句的方式将需要的内容查询出来后…

【人工智能前沿弄潮】—— SAM从提示生成物体mask

SAM从提示生成物体mask Segment Anything Model&#xff08;SAM&#xff09;根据指示所需的对象来预测对象掩码。该模型首先将图像转换为图像嵌入&#xff0c;从而可以从提示中高效地生成高质量的掩码。 SamPredictor类为模型提供了一个简单的接口来提示模型。用户可以首先使…

HTML——格式化文本与段落

&#x1f60a;HTML——格式化文本与段落 &#x1f30f;前言&#x1f3ad;HTML文本标签&#x1f3af;主体内容body标签&#x1f3af;标题字标签&#x1f3af;空格和特殊字符 &#x1f3ad;格式化文本标签&#x1f3af;文本修饰标签&#x1f3af;计算机输出标签&#xff08;成对标…

基于MATLAB小波变换的信号突变点检测

之前在不经意间也有接触过求突变点的问题。在我看来&#xff0c;与其说是求突变点&#xff0c;不如说是我们常常玩的"找不同"。给你两幅图像&#xff0c;让你找出两个图像中不同的地方&#xff0c;我认为这其实也是找突变点在生活中的应用之一吧。回到找突变点位置上…

Linux部署Zabbix主机监控

192.168.136.55 服务端 192.168.136.56 客户端 一、服务端 1.1 安装lamp环境 #关闭防火墙以及SELINUX systemctl disable firewalld systemctl stop firewalld sed -i s/SELINUXenforcing$/SELINUXdisabled/g /etc/selinux/config setenforce 0设置yum源 yum install epe…

Cocos Creator 3.8 后期效果 Shader 编写(2/2) 进阶篇

前言 在上一篇文章中&#xff0c;麒麟子给大家分享了如何在 Cocos Creator 3.8 中的自定义管线中&#xff0c;添加属于自己的后期效果 Shader。 但基于 BlitScreen 的方案&#xff0c;我们只能编写最简单后效 Shader&#xff0c;如果我们想要支持更多复杂的 Shader&#xff0c…

pc端与flutter通信失效, Method not found

报错情况描述&#xff1a;pc端与flutter通信&#xff0c;ios端能实现通信&#xff0c;安卓端通信报错 报错通信代码&#xff1a; //app消息通知window.callbackName function (res) {window?.jsBridge && window.jsBridge?.postMessage(JSON.stringify(res), "…

axios的使用和接口请求统一封装处理

axios官网&#xff1a;axios中文网|axios API 中文文档 | axios 简单封装&#xff1a;配置基础路径和超时时间&#xff0c;还有请求拦截器和响应拦截器 //对axios进行二次封装 import axios from axios//1、利用axios对象的方法create,去创建一个axios实例 const requests …

Redux基础知识,Redux部分源码分析(手写)

复合组件通信的两种方案&#xff1a; 基于props属性实现父子组件通信(或具备相同父亲的兄弟组件)基于context上下文实现祖先和后代组件间的通信(或具备相同祖先的平行组件) 除了以上方案&#xff0c;其实还可以基于公共状态管理&#xff08;Redux&#xff09;实现组件间的通信…

有哪些pdf修改方法?这几种方法学会就够了

有哪些pdf修改方法&#xff1f;PDF是一种非常常见的电子文档格式&#xff0c;它有很多优点&#xff0c;例如可读性强、易于保护、易于打印等等。但是&#xff0c;有时候我们需要对PDF进行修改&#xff0c;例如添加、删除或修改文本、更改图片、合并或分割文件等等。那么今天就给…

对强缓存和协商缓存的理解

浏览器缓存的定义&#xff1a; 浏览器缓存是浏览器在本地磁盘对用户最近请求过的文档进行存储&#xff0c;当访问者再次访问同一页面时&#xff0c;浏览器就可以直接从本地磁盘加载文档。 浏览器缓存分为强缓存和协商缓存。 浏览器是如何使用缓存的&#xff1a; 浏览器缓存…

天津市城市管理委员会莅临道本科技,共同探讨加快推进城市综合执法数字化新模式

2023年8月4日&#xff0c;市城管委处长李春利带队莅临道本科技考察指导&#xff0c;与道本科技董事长王智勇共同探讨加快推进城市综合执法数字化新模式。 会议上&#xff0c;董事长王智勇着重介绍了道本科技最新研发上线的法治大数据应用产品“合规数知法用法平台”。他表示&am…

微信开发之检测僵尸粉的技术实现

简要描述&#xff1a; 检测好友状态 请求URL&#xff1a; http://域名地址/checkZombie 请求方式&#xff1a; POST 请求头Headers&#xff1a; Content-Type&#xff1a;application/jsonAuthorization&#xff1a;login接口返回 参数&#xff1a; 参数名必选类型说明…