如何从另一个Spring启动应用程序访问一个Spring启动应用程序的内存h2数据库

raj*_*raj 6 h2 spring-data spring-data-jpa spring-boot

在我的项目中,我创建了3个春季启动应用程序.第一个spring启动应用程序有h2嵌入式数据库.现在我想直接从我的第二和第三个春季启动应用程序访问这个数据库,而无需编写任何服务来获取这些数据.所以有人能告诉我如何实现这一目标?

Cep*_*pr0 19

您可以将H2 Server设置为Spring Bean.

首先编辑pom.xml - <scope>runtime</scope>从h2依赖项中删除:

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)

然后将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");
    }
}
Run Code Online (Sandbox Code Playgroud)

最后 - 编辑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
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用此连接从外部(例如,使用H2 DB连接到您的应用程序)连接到此H2服务器:

jdbc:h2:tcp://localhost:9092/mem:dbname
Run Code Online (Sandbox Code Playgroud)

作为使用此URL的奖励,您可以直接从IDE连接到应用程序的数据库.

UPDATE

尝试连接到1.5.x版本的Spring Boot应用程序的H2时,可能会出错.在这种情况下,只需将H2的版本更改为前一个版本,例如:

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.193</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

更新2

如果您需要在同一主机上同时运行多个带H2的应用程序,则应在Server.createTcpServermothod中设置不同的H2端口,例如: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");
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用以下网址连接到这些应用的H2 DB:

App1 H2: jdbc:h2:tcp://localhost:9092/mem:dbname
App2 H2: jdbc:h2:tcp://localhost:9093/mem:dbname
Run Code Online (Sandbox Code Playgroud)

  • @Salman`Server`是来自com.h2database:h2`工件的org.h2.tools包的类-请参阅依赖项。并且不要忘记从中删除`&lt;scope&gt; runtime &lt;/ scope&gt;`。 (2认同)
  • 谢谢。顺便说一句,在您尝试连接的其他应用程序的配置文件中,您应该将 `spring.datasource.url` 设置为 `jdbc:h2:tcp://localhost:9092/mem:dbname` (2认同)