测试时连接同一H2文件嵌入式数据库超时问题排查
H2自动混合模式下Serenity BDD测试无法连接数据库问题
问题背景
在Spring Boot应用启动时创建了文件模式的H2数据库,希望运行Serenity BDD集成API测试时连接同一数据库文件,因此采用了H2文档中的**自动混合模式(Automatic Mixed Mode)**方案。
应用配置(application.yaml)
spring: cache: enabled: false sql: init: mode: always datasource: url: jdbc:h2:./../myApp/data/ppyDB;AUTO_SERVER=TRUE;MODE=Oracle username: sa password: sa baseline-on-migrate: true driverClassName: org.h2.Driver jpa: defer-datasource-initialization: false show-sql: true hibernate: ddl-auto: none flyway: enabled: true username: sa password: sa url: jdbc:h2:./../myApp/data/ppyDB;AUTO_SERVER=TRUE;MODE=Oracle locations: classpath:/db/h2/migration h2: console: enabled: true path: /h2-console
测试数据库验证代码
sql = "SELECT * FROM HEADER"; try{ DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.h2.Driver"); dataSource.setUrl("jdbc:h2:./../myApp/data/ppyDB;AUTO_SERVER=TRUE;MODE=Oracle"); dataSource.setUsername("sa"); dataSource.setPassword("sa"); conn = dataSource.getConnection(); String metadataValue = ""; String strMetadata = "test_code"; statement = conn.createStatement(); ResultSet rs = statement.executeQuery(sql); while (rs.next()) { metadataValue = strMetadata.isEmpty() || strMetadata.isBlank() ? rs.getString(0) : rs.getString(strMetadata); } statement.close(); conn.close(); Assert.assertEquals(key, "header.approve", metadataValue);
相关路径信息
- DB文件实际路径:
C:Projects\myApp\data\myDB.mv.db - SerenityBDD集成测试feature文件路径:
C:Projects\myApp\api\src\it\resources\ - SerenityBDD集成测试stepDef路径(上述数据库访问代码所在位置):
C:Projects\myApp\api\src\it\java\stepdefs - 主应用路径:
C:Projects\myApp\api\src\main
报错信息
org.h2.jdbc.JdbcSQLNonTransientConnectionException: Connection is broken: "java.net.SocketTimeoutException: Connect timed out: 172.28.308.1:32632" [90067-214] at org.h2.message.DbException.getJdbcSQLException(DbException.java:678) at org.h2.message.DbException.getJdbcSQLException(DbException.java:477)
myDB.lock.db内容
#FileLock #Wed Apr 12 12:39:46 AEST 2023 server=172.28.308.1\:32632 hostName=AULT-D64WVP99.mshome.net method=file id=18773536407803de631be7d5c6a327adf2b4a815286
疑问
目前可以通过两个H2控制台窗口使用相同URL连接该数据库,但测试代码却无法连接。根据H2文档,新建连接无需指定锁文件中的IP和端口,请问为何会出现这种差异?
内容的提问来源于stack exchange,提问作者Shabar
相关产品推荐
相关产品推荐

