在生产环境中使用嵌入式数据库?

Posted

技术标签:

【中文标题】在生产环境中使用嵌入式数据库?【英文标题】:Using embedded database in production environment? 【发布时间】:2013-12-09 12:25:11 【问题描述】:

我正在使用Spring MVC 3.2 Embedded database (H2) 支持存储任务的实时进度、排队通知和一些临时日志。这种方法的唯一问题是我的数据消失了;如果应用程序重新部署或服务器重新启动。这种情况在生产环境中可能非常罕见,但我仍然想知道在生产环境中使用嵌入式数据库是否是一个不错的选择?..或者有没有办法将嵌入式数据库状态持久化到硬盘,以便下次服务器启动时我们可以将数据库状态恢复到存储的检查点?

谢谢。

【问题讨论】:

【参考方案1】:

嵌入式数据库不适用于生产环境。它们旨在提供更快的开发选项,因为您不需要运行外部数据库的依赖关系。使用嵌入式数据库,您可以以编程方式启动它,并根据您的需要选择性地对其进行初始化。

您的更改在重新部署期间丢失的原因是您使用的是 HsQL 的内存版本而不是进程内(独立文件)模式。您可以使用保持更改持久的独立模式。

In-Process (Standalone) Mode

This mode runs the database engine as part of your application program in the same Java Virtual Machine. For most applications this mode can be faster, as the data is not converted and sent over the network. The main drawback is that it is not possible by default to connect to the database from outside your application. As a result you cannot check the contents of the database with external tools such as Database Manager while your application is running. In 1.8.0, you can run a server instance in a thread from the same virtual machine as your application and provide external access to your in-process database.

The recommended way of using the in-process mode in an application is to use an HSQLDB Server instance for the database while developing the application and then switch to In-Process mode for deployment.

An In-Process Mode database is started from JDBC, with the database file path specified in the connection URL. For example, if the database name is testdb and its files are located in the same directory as where the command to run your application was issued, the following code is used for the connection:

    Connection c = DriverManager.getConnection("jdbc:hsqldb:file:testdb", "sa", "");
The database file path format can be specified using forward slashes in Windows hosts as well as Linux hosts. So relative paths or paths that refer to the same directory on the same drive can be identical. For example if your database path in Linux is /opt/db/testdb and you create an identical directory structure on the C: drive of a Windows host, you can use the same URL in both Windows and Linux:

    Connection c = DriverManager.getConnection("jdbc:hsqldb:file:/opt/db/testdb", "sa", "");
When using relative paths, these paths will be taken relative to the directory in which the shell command to start the Java Virtual Machine was executed. Refer to Javadoc for jdbcConnection for more details.

HSQL documentation

【讨论】:

我使用嵌入式数据库仅用于跟踪当前进度,任务完成后所有更改都将保存到真实数据库服务器这种方法对吗?..谢谢您建议在进程模式下我会尝试出来了。 是否有任何 mysql 独立版本可以放在 Spring Boot JAR 文件的同一目录中...然后您创建一个初始化 MySQL 服务器的 bash 或 windows .bat 脚本.. .then 它运行 Spring Boot JAR 文件 ?....如果该场景有效,我将拥有一个 Spring Boot Stand 桌面 Web 应用程序

以上是关于在生产环境中使用嵌入式数据库?的主要内容,如果未能解决你的问题,请参考以下文章

MySQL 系列 生产标准线上环境安装配置案例及棘手问题解决

用于生产的外部容器中的 Spring Boot 嵌入式容器或 war 文件

我如何将预发布版本推广到生产环境,并嵌入新版本,而无需重新构建?

在生产模式下访问 Play 框架的嵌入式 H2 数据库

WSO2 H2 数据库

如何在多线程环境中使用嵌入式 MySQL?