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

时间:2016-01-23 08:11:09

标签: java mysql spring jdbc connection-pooling

我的应用程序(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>  

3 个答案:

答案 0 :(得分:7)

看起来这是MySQL inactivity timeout - 其中有很多类似的StackOverflow问题(例如hereherehere)。建议通过添加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 />

由于前者完全独立于wait_timeout值,因此会亲自倾向testOnBorrow替换testWhileIdle,但不确定性能如何比较。在JDBC URL中使用autoreconnect=true的替代方案时会个人谨慎,这在错误文本中有所建议 - 请参阅comment here了解原因。

答案 1 :(得分:2)

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

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

添加autoReconnect = true将解决此问题

答案 2 :(得分:2)

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

static {
    try {
        // Create the SessionFactory from app.properties

        Properties properties = new Properties();
        properties.load(new FileInputStream("src//main//resources//app.properties"));
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        configuration.addProperties(properties);
        sessionFactory = configuration.buildSessionFactory();

    } catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed
        LOG.info("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}