无法使用通过 Tomcat 部署的 Spring 应用程序来本地 MySQL 数据库

Posted

技术标签:

【中文标题】无法使用通过 Tomcat 部署的 Spring 应用程序来本地 MySQL 数据库【英文标题】:Unable to local MySQL database with Spring app deployed through Tomcat 【发布时间】:2015-10-18 09:53:12 【问题描述】:

我正在尝试使用 Spring 和 Hibernate 创建一个 Web 应用程序,并通过 Tomcat 8 部署它。我已经在我的机器上本地设置了 mysql 和 Tomcat 8,并且能够将 Web 应用程序部署到它。由于应用程序/tomcat 无法连接到数据库,应用程序无法启动。

我正在按照这里的设置教程(使用 Hibernate 4):Tutorial

当我尝试部署应用程序时,我收到以下错误,我将其缩写为发生的第一个错误:

2015-07-27 20:42:46.768  INFO 77092 --- [n(11)-127.0.0.1] o.h.s.j.c.i.ConnectionProviderInitiator  : HHH000130: Instantiating explicit connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider
2015-07-27 20:42:46.794  WARN 77092 --- [n(11)-127.0.0.1] o.h.e.jdbc.internal.JdbcServicesImpl     : HHH000342: Could not obtain connection to query metadata : Communications link failure
27-Jul-2015 20:42:46.793 SEVERE [RMI TCP Connection(11)-127.0.0.1] org.apache.tomcat.jdbc.pool.ConnectionPool.init Unable to create initial connections of pool.

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:400)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1038)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:339)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2247)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2280)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2079)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:794)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:400)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:399)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:325)
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:307)
at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:200)
at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:699)
at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:633)
at org.apache.tomcat.jdbc.pool.ConnectionPool.init(ConnectionPool.java:484)
at org.apache.tomcat.jdbc.pool.ConnectionPool.<init>(ConnectionPool.java:142)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(DataSourceProxy.java:115)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(DataSourceProxy.java:102)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:126)
at org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider.getConnection(InjectedDataSourceConnectionProvider.java:70)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcServicesImpl.java:242)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:117)
at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:85)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:184)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:156)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1827)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1785)
at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:96)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:915)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:900)
at org.springframework.orm.jpa.vendor.SpringHibernateEjbPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateEjbPersistenceProvider.java:51)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:747)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.context.web.SpringBootServletInitializer.run(SpringBootServletInitializer.java:119)
at org.springframework.boot.context.web.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:110)
at org.springframework.boot.context.web.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:69)
at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:175)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5156)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1648)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:463)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:413)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1466)
at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:76)
at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1307)
at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1399)
at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:828)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:323)
at sun.rmi.transport.Transport$1.run(Transport.java:178)
at sun.rmi.transport.Transport$1.run(Transport.java:175)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:174)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:557)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:812)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:671)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:214)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:298)
... 95 more

应用程序设置 (spring.xml)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
      destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3307/myDatabase" />
    <property name="username" value="Root" />
    <property name="password" value="Root" />
    </bean>


    <!-- Hibernate 4 SessionFactory Bean definition -->
    <bean id="hibernate4AnnotatedSessionFactory"
      class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="annotatedClasses">
        <list>
            <value>com.journaldev.model.Person</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
            <prop key="hibernate.current_session_context_class">thread</prop>
            <prop key="hibernate.show_sql">false</prop>
        </props>
    </property>
    </bean>


    <bean id="userDAO" class="fionn.dao.UserDAOImpl">
    <property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
    </bean>
</beans>

我尝试遵循此处列出的建议:Suggested solution

这似乎是数据库设置的问题,因为我无法通过终端 ping 它。虽然我可以登录:

MySQL 检查

登录:

mysql -u root -p
Enter password: 

mysql> USE myDatabase
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> SHOW TABLES;
+--------------------------+
| Tables_in_gofeisda_fionn |
+--------------------------+
| User                     |
+--------------------------+
1 row in set (0.00 sec)

MySQL 超时:

mysql> show global variables like '%timeout%';
+---------------------------------+-------------------+
| Variable_name                   | Value             |
+---------------------------------+-------------------+
| connect_timeout                 | 10                |
| delayed_insert_timeout          | 300               |
| innodb_flush_log_at_timeout     | 1                 |
| innodb_lock_wait_timeout        | 50                |
| innodb_rollback_on_timeout      | OFF               |
| interactive_timeout             | 28800             |
| lock_wait_timeout               | 31536000          |
| net_read_timeout                | 30                |
| net_write_timeout               | 60                |
| rpl_stop_slave_timeout          | 31536000          |
| slave_net_timeout               | 3600              |
| slow_launch_time                | 2                 |
| wait_timeout                    | 28800             |
+---------------------------------+-------------------+
13 rows in set (0.00 sec)

检查 MySQL 超时:

mysql> show global variables like '%network%';
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| skip_networking | OFF   |
+-----------------+-------+
1 row in set (0.00 sec)

检查 MySQL 主机:

mysql> select user();
+----------------+
| user()         |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.01 sec)

检查 MySQL 端口

mysql> show variables like '%port%';
+---------------------+-------+
| Variable_name       | Value |
+---------------------+-------+
| innodb_support_xa   | ON    |
| large_files_support | ON    |
| port                | 3307  |
| report_host         |       |
| report_password     |       |
| report_port         | 3307  |
| report_user         |       |
+---------------------+-------+
7 rows in set (0.01 sec)

检查跳过网络

mysql> show global variables like '%skip%';
+------------------------+-------+
| Variable_name          | Value |
+------------------------+-------+
| skip_external_locking  | ON    |
| skip_name_resolve      | OFF   |
| skip_networking        | OFF   |
| skip_show_database     | OFF   |
| slave_skip_errors      | OFF   |
| sql_slave_skip_counter | 0     |
+------------------------+-------+
6 rows in set (0.00 sec)

Ping 检查

127.0.0.1

$ ping 127.0.0.1
PING 127.0.0.1 (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.079 ms
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.194 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.200 ms
64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.166 ms
64 bytes from 127.0.0.1: icmp_seq=4 ttl=64 time=0.171 ms
64 bytes from 127.0.0.1: icmp_seq=5 ttl=64 time=0.216 ms
^C
--- 127.0.0.1 ping statistics ---
6 packets transmitted, 6 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.079/0.171/0.216/0.045 ms

本地主机

$ ping localhost
PING localhost (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.058 ms
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.054 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.202 ms
64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.071 ms
64 bytes from 127.0.0.1: icmp_seq=4 ttl=64 time=0.119 ms
64 bytes from 127.0.0.1: icmp_seq=5 ttl=64 time=0.222 ms
^C
--- localhost ping statistics ---
6 packets transmitted, 6 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.054/0.121/0.222/0.068 ms

本地 MySQL 端口

$ ping localhost:3307
PING localhost:3307 (198.105.254.228): 56 data bytes
Request timeout for icmp_seq 0
Request timeout for icmp_seq 1
Request timeout for icmp_seq 2
Request timeout for icmp_seq 3
Request timeout for icmp_seq 4
Request timeout for icmp_seq 5
^C
--- localhost:3307 ping statistics ---
7 packets transmitted, 0 packets received, 100.0% packet loss

我还需要什么来确保数据库/tomcat/应用程序设置正确。

更新 1:

按照此处概述的说明进行操作:setup

我在配置文件中添加了绑定地址参数,使用127.0.0.1,并将端口设置为3306。我觉得不行,因为重启MySQL后,端口仍然设置为3307。

【问题讨论】:

你是否取消了mysql配置文件中的bind-address指令的注释:my.cnf? 好吧,既然你在控制台上用root用户连接了,你有没有尝试在你的配置中使用它作为连接用户和密码? 另外,您是否在 mysql 上创建了用户 pankaj ?你试过在 mysql 控制台上连接它吗? my.cnf 在 OS X 上的位置? 我创建了一个my.cnf填写这里的说明,并重启了MySQL服务。而且没有骰子。 【参考方案1】:

让我们从基本原理来看。

您正在使用的 JDBC URL,表示您正在尝试连接到“localhost:3307”

java.net.ConnectException: Connection refused 表示数据库没有在您的客户端尝试使用的 IP 地址和端口号上侦听请求。

那么为什么会出错呢?

可能是数据库根本没有运行,但您可能已经消除了这种情况。 (可以从命令行运行mysql客户端吗?)

可能是您(或某人)错误地将localhost 配置为解析为127.0.0.1 以外的其他内容。 (有些人会做疯狂的事……)

但我认为最可能的解释是 MySQL 没有监听请求 127.0.0.1。

确定这一点的一种方法是启动数据库,然后运行“netstat -an | grep LISTEN | grep tcp”。这将向您显示当前正在“侦听”的所有 IP 地址和端口号。确保包含您尝试使用的地址/端口组合。

(请注意,IPv4 地址0.0.0.0 表示任何地址。它是通配符。)

一旦你弄清楚服务器正在监听什么,你就可以决定是更改 JDBC URL 以匹配它,还是让服务器监听你想要使用的 IP/端口。


其他人建议用户名和密码有问题。这些建议是红鲱鱼。如果这是问题所在,那么例外情况会有所不同。

【讨论】:

我从命令行仔细检查了 MySQL,它正在运行。我可以使用“mysql -u root -p”登录。我仔细检查了本地主机,它设置为 127.0.0.1。运行 net stat 命令,第一个列表是监听 127.0.0.1:3307。当我停止 MySQL 服务时,它不再列出。当我重新启动它时,它会再次列出。奇怪的是我添加了 /etc/my.cnf 只有“bind-address = 127.0.0.1”和“port = 3306”。那不应该把监听端口设置为3306吗?【参考方案2】:

我解决了这个问题更新my.cnf文件搜索:

skip-networking

并将其更新为:

#skip-networking

终于重启Mysql

【讨论】:

【参考方案3】:

确保您的 MySql Server 服务已启动,如果未启动,请转到 controlPanel -> Services 并搜索 Mysql80 并启动它。

【讨论】:

以上是关于无法使用通过 Tomcat 部署的 Spring 应用程序来本地 MySQL 数据库的主要内容,如果未能解决你的问题,请参考以下文章

部署在tomcat上的Spring Boot无法启动

Spring MVC项目无法部署到tomcat中运行。

Spring Boot在部署到Tomcat期间无法加载外部jar

多个Spring Boot项目部署在一个Tomcat容器无法启动

Spring 应用程序无法在 Tomcat 上部署:applicationContext 有啥问题?

使用 Tomcat 进行 Spring Boot 部署