Arm*_*man 6 java mysql jdbc maven docker
当测试集成开始时,我可以使用以下命令连接到终端上的容器上的mysql:
mysql -h 127.0.0.1 -P 32795 -uroot -p
Run Code Online (Sandbox Code Playgroud)
并且每一件事情都很好,但是当我想用java代码连接这个代码时,在java应用程序中连接mysql:
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:" + System.getProperty("mysqlPort") + "/dashboardmanager",
"root",
"root"
);
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: Cannot create PoolableConnectionFactory (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.)
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:80) ~[spring-jdbc-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:615) ~[spring-jdbc-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:866) ~[spring-jdbc-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:927) ~[spring-jdbc-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:937) ~[spring-jdbc-4.2.4.RELEASE.jar:4.2.4.RELEASE]
Run Code Online (Sandbox Code Playgroud)
我试过了:
export _JAVA_OPTIONS="-Djava.net.preferIPv4Stack=true"
Run Code Online (Sandbox Code Playgroud)
和
System.setProperty("java.net.preferIPv4Stack" , "true");
Run Code Online (Sandbox Code Playgroud)
但没有改变.
Docker Maven插件 Conf:
<plugin>
<groupId>org.jolokia</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>${docker-maven-plugin.version}</version>
<configuration>
<images>
<image>
<name>mysql:5.7.11</name>
<run>
<env>
<MYSQL_ROOT_PASSWORD>root</MYSQL_ROOT_PASSWORD>
<MYSQL_DATABASE>dashboardmanager</MYSQL_DATABASE>
</env>
<ports>
<port>mysqlPort:3306</port>
</ports>
</run>
</image>
</images>
</configuration>
<executions>
<execution>
<id>start</id>
<phase>pre-integration-test</phase>
<goals>
<goal>start</goal>
</goals>
</execution>
<execution>
<id>stop</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
Run Code Online (Sandbox Code Playgroud)
问题是这样的:
MySql 启动过程大约需要 40 秒,所以我应该停留大约 40 秒,然后尝试连接到 mySql,就这么简单:)
或者我可以在 pom.xml 中使用这些设置:
<image>
<name>mysql:5.7.11</name>
<alias>mysqlContainer</alias>
<run>
<env>
<MYSQL_ROOT_PASSWORD>root</MYSQL_ROOT_PASSWORD>
<MYSQL_DATABASE>dashboard</MYSQL_DATABASE>
</env>
<ports>
<port>mysqlPort:3306</port>
</ports>
<wait>
<log>.*port: 3306 MySQL Community Server.*</log>
<time>120000</time>
</wait>
</run>
</image>
Run Code Online (Sandbox Code Playgroud)