java - 备份和恢复 HsqlDb 嵌入文件(非数据库)

标签 java spring backup spring-data-jpa hsqldb

外面每个人都在谈论备份Hsqldb,但我需要的是备份嵌入的文件...

我正在使用Spring JPA,并且应用程序始终在运行,因此文件正在使用中,而且由于没有DBMS,我想知道是否有备份和恢复的方法? 如果有请指导一下...

否则,我想在以某种方式(不知道如何)将 spring JPA 置于离线模式之后复制数据库文件,然后压缩这些文件,我在 java 中不知道这些文件,然后让用户下载它,如果 spring 允许的话......不知何故(因为我使用独立的 spring boot,它是一个文件,并且它不提供很多那些奇特的文件夹,我们可以将它们作为网站 url 指向......)

最终在任何情况下我都想将文件发送给客户端。

抱歉,如果我对此一无所知,我来自 C#,五年后,这是我第二次使用 Java,我从来都不是专业人士。

更新

虽然我不确定是否可以从运行数据库制作一个zip文件,并将其存储在那个地方...我通过搜索编写此代码,我找到了几种返回当前目录的方法,但没有一个指出到我想要的目录...其中之一,在调试时它指向非常内部的位置,例如 targer/class/x/y/z,在我将其打包到 jar 文件后,它可能会有所不同,另一个指向 C/..../temp,...我需要写入我的数据库文件所在的位置,然后传递这些文件以制作 zip 文件功能,并告诉用户下载文件

@RestController
@RequestMapping(value = "/rest/database-manager")
public class DatabaseManager {

    private ServletContext servletContext;
    private final Environment env;

    @Autowired
    public DatabaseManager(Environment env, ServletContext servletContext) {
        this.env = env;
        this.servletContext = servletContext;
    }

    @RequestMapping(value = "/get-backup", method=RequestMethod.GET)
    private FileSystemResource getBackup() throws IOException {
        //String directory = DemoApplication.class.getResource("").getPath();
        String outputLocation = servletContext.getRealPath("./");
        String dataBaseFilePath = servletContext.getRealPath(env.getProperty("application.database-file-location"));
        Calendar cal = new GregorianCalendar();
        String zipFile = outputLocation + "/backup-"
                + StrMgr.leftPad(String.valueOf(cal.get(Calendar.YEAR)), 4, "0")
                + StrMgr.leftPad(String.valueOf(cal.get(Calendar.MONTH)), 2, "0")
                + StrMgr.leftPad(String.valueOf(cal.get(Calendar.DAY_OF_MONTH)), 2, "0")
                + "-"
                + StrMgr.leftPad(String.valueOf(cal.get(Calendar.HOUR)), 2, "0")
                + StrMgr.leftPad(String.valueOf(cal.get(Calendar.MINUTE)), 2, "0")
                + StrMgr.leftPad(String.valueOf(cal.get(Calendar.SECOND)), 2, "0")
                + ".zip";
        ZipUtil.ToZip(new String[]{""}, zipFile);
        return new FileSystemResource(zipFile);
    }
}

zip函数:

public class ZipUtil {
    public static void ToZip(String inputFiles[], String outputFile) throws IOException {
        //create byte buffer
        byte[] buffer = new byte[1024];

                /*
                 * To create a zip file, use
                 *
                 * ZipOutputStream(OutputStream out)
                 * constructor of ZipOutputStream class.
                */

        //create object of FileOutputStream
        FileOutputStream fout = new FileOutputStream(outputFile);

        //create object of ZipOutputStream from FileOutputStream
        ZipOutputStream zout = new ZipOutputStream(fout);

        for (int i = 0; i < inputFiles.length; i++) {
            //create object of FileInputStream for source file
            FileInputStream fin = new FileInputStream(inputFiles[i]);

                        /*
                         * To begin writing ZipEntry in the zip file, use
                         *
                         * void putNextEntry(ZipEntry entry)
                         * method of ZipOutputStream class.
                         *
                         * This method begins writing a new Zip entry to
                         * the zip file and positions the stream to the start
                         * of the entry data.
                         */

            zout.putNextEntry(new ZipEntry(inputFiles[i]));

                        /*
                         * After creating entry in the zip file, actually
                         * write the file.
                         */
            int length;

            while ((length = fin.read(buffer)) > 0) {
                zout.write(buffer, 0, length);
            }

                        /*
                         * After writing the file to ZipOutputStream, use
                         *
                         * void closeEntry() method of ZipOutputStream class to
                         * close the current entry and position the stream to
                         * write the next entry.
                         */

            zout.closeEntry();

            //close the InputStream
            fin.close();

        }


        //close the ZipOutputStream
        zout.close();
    }
}

完整答案:

我不确定 Produce 是否会执行任何操作,因为我直接写入内部响应,并返回 void

我的回应方式:

    @RequestMapping(value = "/get-backup", method = RequestMethod.GET)
    private void getBackup(HttpServletResponse response) throws IOException {
        /*//String directory = DemoApplication.class.getResource("").getPath();
        String outputLocation = servletContext.getRealPath("./");
        String dataBaseFilePath = servletContext.getRealPath(env.getProperty("application.database-file-location"));
        Calendar cal = new GregorianCalendar();
        String zipFile = outputLocation + "/backup-"
                + StrMgr.leftPad(String.valueOf(cal.get(Calendar.YEAR)), 4, "0")
                + StrMgr.leftPad(String.valueOf(cal.get(Calendar.MONTH)), 2, "0")
                + StrMgr.leftPad(String.valueOf(cal.get(Calendar.DAY_OF_MONTH)), 2, "0")
                + "-"
                + StrMgr.leftPad(String.valueOf(cal.get(Calendar.HOUR)), 2, "0")
                + StrMgr.leftPad(String.valueOf(cal.get(Calendar.MINUTE)), 2, "0")
                + StrMgr.leftPad(String.valueOf(cal.get(Calendar.SECOND)), 2, "0")
                + ".zip";

        SQLQuery query = session.createSQLQuery("BACKUP DATABASE TO '/tmp/backup.tar.gz' BLOCKING");
        query.executeUpdate();*/

        File zipFile = null;

        Calendar cal = new GregorianCalendar();
        String prefix = "DBK-"
                + StrMgr.leftPad(String.valueOf(cal.get(Calendar.YEAR)), 4, "0")
                + StrMgr.leftPad(String.valueOf(cal.get(Calendar.MONTH)), 2, "0")
                + StrMgr.leftPad(String.valueOf(cal.get(Calendar.DAY_OF_MONTH)), 2, "0")
                + "-"
                + StrMgr.leftPad(String.valueOf(cal.get(Calendar.HOUR)), 2, "0")
                + StrMgr.leftPad(String.valueOf(cal.get(Calendar.MINUTE)), 2, "0")
                + StrMgr.leftPad(String.valueOf(cal.get(Calendar.SECOND)), 2, "0");
        String suffix = ".tar.gz";
        zipFile = File.createTempFile(prefix, suffix);

        zipFile.delete();

        databaseManagerRepository.Backup(zipFile.getAbsolutePath());

        response.setContentType("application/gzip");
        response.setHeader("Content-disposition", "attachment; filename=" + zipFile.getName());

//            OutputStream out = response.getOutputStream();
//            FileInputStream in = new FileInputStream(zipFile);
            /*
             * copy from in to out
             */
        OutputStream out = null;
        FileInputStream in = null;
        try {
            out = response.getOutputStream();
            in = new FileInputStream(zipFile);

            byte[] buffer = new byte[4096]; // To hold file contents
            int bytes_read; // How many bytes in buffer

            // Read a chunk of bytes into the buffer, then write them out,
            // looping until we reach the end of the file (when read() returns
            // -1). Note the combination of assignment and comparison in this
            // while loop. This is a common I/O programming idiom.
            while ((bytes_read = in.read(buffer)) != -1)
                // Read until EOF
                out.write(buffer, 0, bytes_read); // write
        }
        catch (Exception ex){
            System.out.print(ex.getMessage());
        }
        // Always close the streams, even if exceptions were thrown
        finally {
            if (in != null)
                try {
                    in.close();
                } catch (IOException e) {
                    ;
                }
            if (out != null)
                try {
                    out.close();
                } catch (IOException e) {
                    ;
                }
        }

        zipFile.delete();
    }

我的备份 native SQL 操作执行器

@Repository
public class DatabaseManagerRepository {
    @PersistenceContext
    private EntityManager entityManager;

    /*The query force us to use transaction, and since the DB is online and we use spring, it also force us to use spring transaction*/
    @Transactional(rollbackFor = {Exception.class})
    public void Backup(String outputDir) {
            //NOT BLOCKING -> For large database, backup is performed while the database perform other operations
            //AS FILES -> We only define directory not the file itself
            Query q = entityManager.createNativeQuery("BACKUP DATABASE TO '" + outputDir + "' BLOCKING"/*" AS FILES"*/);
            q.executeUpdate();
    }
}

最佳答案

备份与 HSQLDB 服务器或嵌入式数据库相同。您执行SQL语句:

BACKUP DATABASE TO <directory name> BLOCKING AS FILES

目录名称是存储备份文件的目标目录的路径。例如将数据库备份到“C://db_backups/”作为文件阻塞

http://hsqldb.org/doc/2.0/guide/management-chapt.html#mtc_online_backup

AS FILES 备份数据库创建一组可以压缩的文件。

关于java - 备份和恢复 HsqlDb 嵌入文件(非数据库),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41291807/

相关文章:

batch-file - 如何使用批处理文件复制(和增加)文件的多个实例

svn - 将转储的 SVN 存储库导入 VisualSVN Server

java - Vertx 代码生成失败 - ARRAY 类型非法类型 java.lang.String[]

java.lang.NoClassDefFoundError : com. google.ads.AdView

java - 如何将数据从数据库表加载到浏览器并将数据更新回数据库?

Java POI使用Maven资源过滤器时出现InvalidOperationException

java - 单元测试在构建服务中失败但在本地失败

java - 为什么 Spring 使用 ForkPoolJoin 而不是带有 @Async 的 ThreadPoolTask​​Executor?

open-source - 使用 torrent 协议(protocol)的去中心化备份

java - RecyclerView 的 onBindview Holder 不适用于第二个位置,但我在 getItemCount 中计数为 3