【问题标题】:How to enable H2 Database Server Mode in Spring Boot如何在 Spring Boot 中启用 H2 数据库服务器模式
【发布时间】:2019-09-13 17:57:39
【问题描述】:

我正在使用带有 Spring Boot 文件的 H2 数据库。

在我的 application.properties 中,我有这个条目:

spring.datasource.url=jdbc:h2:file:c:/Testprojekte/spring-boot-h2-db

但是现在我希望能够在运行应用程序时查看数据库,目前这是不可能的,因为我需要让数据库在服务器模式下运行才能这样做。在文档中,我发现我必须将 AUTO_SERVER=TRUE 添加到 URL 但这并不能解决问题。

那么,为了能够同时从不同进程连接到该数据库,我需要进行哪些更改?

感谢您的帮助! 托尔斯滕

【问题讨论】:

    标签: java spring-boot spring-data-jpa h2


    【解决方案1】:

    您可以将 H2 TCP 服务器作为 bean 启动:

    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <!-- <scope>runtime</scope> -->
    </dependency>
    
    @SpringBootApplication
    public class Application {
    
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    
        @Bean(initMethod = "start", destroyMethod = "stop")
        public Server h2Server() throws SQLException {
            return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9092");
        }
    }
    

    然后使用以下参数(密码 - 空)从您的 IDE 连接到它:

    url: jdbc:h2:tcp://localhost:9092/mem:testdb
    user: sa
    

    更多信息是herehere

    【讨论】:

    • 我必须将它添加到 url:jdbc:h2:tcp://localhost:9090/~/database-name,因为我使用的是文件 h2 数据库。
    • 如果 db 位于同一主机上,从性能角度来看,这不是一个好的选择,因为您使用内核调用和完整的 tcp 堆栈调用来访问 db。并且该配置不是访问 h2 控制台所必需的,它可以嵌入但带有额外的 h2 servlet
    【解决方案2】:

    您可以使用浏览器中的 Web 界面启用 h2 Web 控制台以访问内存或文件数据库中的 h2。

    为此添加 application.properties 行:

    spring.h2.console.enabled=true
    spring.h2.console.path=/h2-console
    

    然后重新启动您的 Spring Boot 应用程序并使用您的浏览器检查 http://localhost:8080/h2-console

    【讨论】:

      猜你喜欢
      • 2010-12-02
      • 1970-01-01
      • 2012-03-08
      • 2016-09-01
      • 2013-01-24
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 2018-06-13
      相关资源
      最近更新 更多