H2 数据库 - 为多个 spring 启动应用程序使用持久存储

H2 Database - using persistent storage for multiple spring boot applications

我想将 h2 数据库用于多个 spring 启动应用程序。我已经阅读了几篇文章,他们告诉您如何配置 h2 db,但使用内存数据库,其中数据存储是临时的。我只想知道是否有可能拥有持久存储,并为 h2 db 提供多个 spring 启动应用程序。任何帮助或 link 将不胜感激。谢谢

h2 可以将数据存储在文件或内存中。对于基于文件的存储,jdbc url 的格式应为 jdbc:h2:[file:][]。对于内存,jdbc url 看起来像 jdbc:h2:mem:。有关数据库 url 格式的详细信息,请参阅 http://www.h2database.com/html/features.html#database_url

似乎有一种方法可以让多个应用程序使用 [=] 末尾的 属性 AUTO_SERVER=TRUE 访问 H2 数据库(不是内存数据库)的同一文件21=]。这被称为Automatic Mixed Mode for H2 database

Automatic Mixed Mode

Multiple processes can access the same database without having to start the server manually. To do that, append ;AUTO_SERVER=TRUE to the database URL. You can use the same database URL independent of whether the database is already open or not. This feature doesn't work with in-memory databases. Example database URL:

jdbc:h2:/data/test;AUTO_SERVER=TRUE Use the same URL for all connections to this database. Internally, when using this mode, the first connection to the database is made in embedded mode, and additionally a server is started internally (as a daemon thread). If the database is already open in another process, the server mode is used automatically. The IP address and port of the server are stored in the file .lock.db, that's why in-memory databases can't be supported.

The application that opens the first connection to the database uses the embedded mode, which is faster than the server mode. Therefore the main application should open the database first if possible. The first connection automatically starts a server on a random port. This server allows remote connections, however only to this database (to ensure that, the client reads .lock.db file and sends the random key that is stored there to the server). When the first connection is closed, the server stops. If other (remote) connections are still open, one of them will then start a server (auto-reconnect is enabled automatically).

All processes need to have access to the database files. If the first connection is closed (the connection that started the server), open transactions of other connections will be rolled back (this may not be a problem if you don't disable autocommit). Explicit client/server connections (using jdbc:h2:tcp:// or ssl://) are not supported. This mode is not supported for in-memory databases.

Here is an example how to use this mode. Application 1 and 2 are not necessarily started on the same computer, but they need to have access to the database files. Application 1 and 2 are typically two different processes (however they could run within the same process).

OP 面临的问题正如他评论的那样:

I am able to connect to the h2 database in my main application using file storage. However when I try to connect from my 2nd application to the same db, then the file lock error comes up

原因是这仅在 OP 未启用的自动混合模式下允许。