在我的项目中,我创建了3个spring boot应用程序。第一个spring boot应用程序具有h2嵌入式数据库。现在,我想直接从第二和第三次Spring Boot应用程序访问此数据库,而无需编写任何服务来获取此数据。那么有人可以告诉我如何实现这一目标吗?
您可以将H2服务器设置为Spring Bean。
首先编辑pom.xml-<scope>runtime</scope>
从h2依赖项中删除:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
然后将H2服务器bean添加到SpringBootApplication
或Configuration
类中:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
/**
* Start internal H2 server so we can query the DB from IDE
*
* @return H2 Server instance
* @throws SQLException
*/
@Bean(initMethod = "start", destroyMethod = "stop")
public Server h2Server() throws SQLException {
return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9092");
}
}
最后-编辑application.properties
-设置数据库名称:
spring.datasource.url=jdbc:h2:mem:dbname
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create
然后,您可以使用以下连接从外部连接到该H2服务器(例如,通过H2 DB连接到您的应用程序):
jdbc:h2:tcp://localhost:9092/mem:dbname
作为奖励,使用此URL,您可以直接从IDE连接到应用程序的数据库。
更新
尝试连接到1.5.x版本的Spring Boot应用程序的H2时,可能会出现错误。在这种情况下,只需将H2的版本更改为先前的版本,例如:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.193</version>
</dependency>
更新2
如果需要在同一主机上同时运行带有H2的多个应用程序,则应在它们的主机上分别设置不同的H2端口Server.createTcpServer
,例如:9092、9093等。
// First App
@Bean(initMethod = "start", destroyMethod = "stop")
public Server h2Server() throws SQLException {
return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9092");
}
// Second App
@Bean(initMethod = "start", destroyMethod = "stop")
public Server h2Server() throws SQLException {
return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9093");
}
然后,您可以使用以下网址连接到这些应用程序的H2 DB:
App1 H2: jdbc:h2:tcp://localhost:9092/mem:dbname
App2 H2: jdbc:h2:tcp://localhost:9093/mem:dbname
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句