栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

您可以将H2服务器设置为Spring Bean。

首先编辑pom.xml-

<scope>runtime</scope>
从h2依赖项中删除:

<dependency>    <groupId>com.h2database</groupId>    <artifactId>h2</artifactId></dependency>

然后将H2服务器bean添加到

SpringBootApplication
Configuration
类中:

@SpringBootApplicationpublic 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");    }}

最后-编辑

application.properties
-设置数据库名称:

spring.datasource.url=jdbc:h2:mem:dbnamespring.datasource.driverClassName=org.h2.Driverspring.datasource.username=saspring.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:dbnameApp2 H2: jdbc:h2:tcp://localhost:9093/mem:dbname


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/377004.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号