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

时间:2016-12-22 21:20:21

标签: java spring backup spring-data-jpa hsqldb

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

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

否则,我虽然复制了数据库文件,但是以某种方式(不知道如何)将spring JPA置于离线模式,然后将那些我在java中不知道的文件压缩,然后让它们用户下载它,如果弹簧允许它......某种程度上(因为我使用独立的弹簧启动,这是一个单独的文件,它并没有提供很多那些花哨的文件夹,我们可以指出他们作为网站网址...)

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

很抱歉,如果我不知道这一点,我来自C#,5年后,这是我第二次使用Java,我从来没有在其中使用过它。

更新

虽然我不确定我是否可以从运行数据库制作一个zip文件,并将其存储在那个地方......我通过搜索编写了这个代码,我找到了几个返回当前目录的方法,但是没有他们指向我想要的目录...其中一个,在调试它指向非常内部的位置,像targer / class / x / y / z,在我将它打包到jar文件后,它可能是不同的,另一个指向C /.... / temp,...我需要写入我的DB文件所在的位置,然后传递这些文件来制作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();
    }
}

完整答案:

我不确定Produ是否会做任何事情,因为我直接写入内部的回复,然后返回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();
    }

我的备份本机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();
    }
}

1 个答案:

答案 0 :(得分:1)

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

BACKUP DATABASE TO <directory name> BLOCKING AS FILES

目录名是存储备份文件的目标目录的路径。例如BACKUP DATABASE TO 'C://db_backups/' BLOCKING AS FILES

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

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