com.mysql.jdbc.exceptions.jdbc4.CommunicationsException MySQL + Apache Tomcat 7

Posted

技术标签:

【中文标题】com.mysql.jdbc.exceptions.jdbc4.CommunicationsException MySQL + Apache Tomcat 7【英文标题】: 【发布时间】:2016-04-29 21:46:05 【问题描述】:

我的应用程序(Spring 4 MVC / Hibernate 4 / mysql / Maven)使用基于注释的配置将 Spring 与 Hibernate 集成。几个小时后它没有使用数据库,我总是看到这个错误:

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 84,510,841 milliseconds ago.  The last packet sent successfully to the server was 84,510,841 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.
    sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1121)
    com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3938)
    com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2551)
    com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2731)
    com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2809)
    com.mysql.jdbc.ConnectionImpl.setAutoCommit(ConnectionImpl.java:5333)
    sun.reflect.GeneratedMethodAccessor58.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:606)
    org.apache.tomcat.jdbc.pool.ProxyConnection.invoke(ProxyConnection.java:126)
    org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:109)
    org.apache.tomcat.jdbc.pool.DisposableConnectionFacade.invoke(DisposableConnectionFacade.java:80)
    com.sun.proxy.$Proxy33.setAutoCommit(Unknown Source)
    org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.begin(AbstractLogicalConnectionImplementor.java:67)
    org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.begin(LogicalConnectionManagedImpl.java:238)
    org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.begin(JdbcResourceLocalTransactionCoordinatorImpl.java:213)
    org.hibernate.engine.transaction.internal.TransactionImpl.begin(TransactionImpl.java:52)
    org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1512)
    org.hibernate.jpa.internal.TransactionImpl.begin(TransactionImpl.java:45)
    org.springframework.orm.jpa.vendor.HibernateJpaDialect.beginTransaction(HibernateJpaDialect.java:170)
    org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:380)
    org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
    org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:427)
    org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276)
    org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
    com.sun.proxy.$Proxy118.findAll(Unknown Source)
    com.ideefe.iot.controller.AppController.listDevices(AppController.java:49)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:606)
    org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.springframework.web.multipart.support.MultipartFilter.doFilterInternal(MultipartFilter.java:118)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

这里是 MySQL my.cnf 文件:

devuser@localhost:/etc/apache2$ more /etc/mysql/my.cnf
#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
# 
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html

# This will be passed to all mysql clients
# It has been reported that passwords should be enclosed with ticks/quotes
# escpecially if they contain "#" chars...
# Remember to edit /etc/mysql/debian.cnf when changing the socket location.
[client]
port        = 3306
socket      = /var/run/mysqld/mysqld.sock

# Here is entries for some specific programs
# The following values assume you have at least 32M ram

# This was formally known as [safe_mysqld]. Both versions are currently parsed.
[mysqld_safe]
socket      = /var/run/mysqld/mysqld.sock
nice        = 0

[mysqld]
#
# * Basic Settings
#
user        = mysql
pid-file    = /var/run/mysqld/mysqld.pid
socket      = /var/run/mysqld/mysqld.sock
port        = 3306
basedir     = /usr
datadir     = /var/lib/mysql
tmpdir      = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address        = 127.0.0.1
#
# * Fine Tuning
#
key_buffer      = 32M
max_allowed_packet  = 1M
thread_stack        = 128K
thread_cache_size       = 8
# This replaces the startup script and checks MyISAM tables if needed
# the first time they are touched
myisam-recover         = BACKUP
max_connections        = 75
table_cache            = 32
#thread_concurrency     = 10
#
# * Query Cache Configuration
#
query_cache_limit   = 1M
query_cache_size        = 16M
#
# * Logging and Replication
#
# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.
# As of 5.1 you can enable the log at runtime!
#general_log_file        = /var/log/mysql/mysql.log
#general_log             = 1
#
# Error log - should be very few entries.
#
log_error = /var/log/mysql/error.log
#
# Here you can see queries with especially long duration
#log_slow_queries   = /var/log/mysql/mysql-slow.log
#long_query_time = 2
#log-queries-not-using-indexes
#
# The following can be used as easy to replay backup logs or for replication.
# note: if you are setting up a replication slave, see README.Debian about
#       other settings you may need to change.
#server-id      = 1
#log_bin            = /var/log/mysql/mysql-bin.log
expire_logs_days    = 10
max_binlog_size         = 100M
#binlog_do_db       = include_database_name
#binlog_ignore_db   = include_database_name
#
# * InnoDB
#
# InnoDB is enabled by default with a 10MB datafile in /var/lib/mysql/.
# Read the manual for more InnoDB related options. There are many!
#
# * Security Features
#
# Read the manual, too, if you want chroot!
# chroot = /var/lib/mysql/
#
# For generating SSL certificates I recommend the OpenSSL GUI "tinyca".
#
# ssl-ca=/etc/mysql/cacert.pem
# ssl-cert=/etc/mysql/server-cert.pem
# ssl-key=/etc/mysql/server-key.pem



[mysqldump]
quick
quote-names
max_allowed_packet  = 16M

[mysql]
#no-auto-rehash # faster start of mysql but no tab completition

[isamchk]
key_buffer      = 16M

#
# * IMPORTANT: Additional settings that can override those from this file!
#   The files must end with '.cnf', otherwise they'll be ignored.
#
!includedir /etc/mysql/conf.d/

我使用的连接池定义如下:

<?xml version="1.0" encoding="UTF-8"?> 
<Context>
    <!-- Especifica un DataSource JDBC. --> 
    <Resource name="jdbc/devicesDS"
              auth="Container"
              type="javax.sql.DataSource"
              maxActive="10"
              maxIdle="4"
              username="root"
              password="SrbBfsatn640^"
              driverClassName="com.mysql.jdbc.Driver"
              url="jdbc:mysql://localhost:3306/devices?autoReconnect=true"
              validationQuery="select 1 from dual" />
</Context>  

【问题讨论】:

你在使用连接池吗?如果有,是哪一个?日志中所说的问题“您应该在应用程序中使用之前考虑过期和/或测试连接有效性,增加客户端超时的服务器配置值,或者使用连接器/J连接属性'autoReconnect = true'来避免这个问题" 只需使用select 1 作为验证查询。如果您编写select 1 from dual,则每个验证查询都会返回dual 表中的每一行。 【参考方案1】:

看起来这是 MySQL inactivity timeout - 围绕它有很多类似的 *** 问题(例如 here、here 和 here)。建议通过添加testOnBorrow=true 来更改您的连接池设置,即:

<Resource name="jdbc/devicesDS"
          auth="Container"
          type="javax.sql.DataSource"
          maxActive="10"
          maxIdle="4"
          username="root"
          password="SrbBfsatn640^"
          driverClassName="com.mysql.jdbc.Driver"
          url="jdbc:mysql://localhost:3306/devices?autoReconnect=true"
          validationQuery="select 1 from dual"
          testOnBorrow=true />

我个人倾向于testOnBorrow 而不是testWhileIdle,因为前者完全独立于wait_timeout 值(但不确定性能比较如何)。在 JDBC URL 中使用 autoreconnect=true 的替代品时也要谨慎:MySQL Connector/J documentation 不建议这样做,因为当应用程序不处理 SQLExceptions 时,它会产生与会话状态和数据一致性相关的副作用正确,并且仅在您无法配置应用程序以正确处理因死连接和陈旧连接而导致的 SQLExceptions 时使用”

【讨论】:

【参考方案2】:

在您的应用程序中,与数据库 mysql 的连接字符串应为:

jdbc:mysql://host:port/schema?autoReconnect=true

添加 autoReconnect=true 将解决此问题

【讨论】:

【参考方案3】:

在尝试了每个配置、自动重新连接等之后,我在其他应用程序实现中遇到了这个问题。 我发现解决这个问题的唯一方法是制作一个调度事件,每小时调用一个测试查询来 ping 数据库,强制它刷新连接。

query("SELECT version()");

【讨论】:

以上是关于com.mysql.jdbc.exceptions.jdbc4.CommunicationsException MySQL + Apache Tomcat 7的主要内容,如果未能解决你的问题,请参考以下文章

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:重复条目 '' 键 'PRIMARY'

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:通信链路故障?

错误 com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:表不存在

使用 JDBC 访问远程 MySQL 数据库时出现 com.mysql.jdbc.exceptions.jdbc4.CommunicationsException

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:通信链路故障