모든 사람들이 외부에서 Hsqldb 백업에 대해 이야기하지만 필요한 것은 포함 된 파일을 백업하는 것입니다.
Spring JPA를 사용하고 있으며 응용 프로그램이 항상 실행 중이므로 파일이 사용 중이며 DBMS가 없기 때문에 백업 및 복원 방법이 있는지 궁금합니다. 있으면 안내 해주세요 ...
그렇지 않으면 데이터베이스 파일을 복사하는 중이지만 어떻게 든 (방법을 모르겠 음) spring JPA를 오프라인 모드로 설정 한 다음 Java에서 모르는 파일을 ZIP으로 압축 한 다음 사용자가 봄이면 다운로드하도록하십시오. 어떻게 든 ... 어떻게 든 (단일 파일 인 독립 실행 형 스프링 부트를 사용하고 웹 사이트 URL로 가리킬 수있는 멋진 폴더를 많이 제공하지 않기 때문에 ...)
결국 어떤 시나리오에서든 파일을 클라이언트에 보내고 싶습니다.
내가 이것에 대해 아는 것이 없다면 미안하다. 나는 C #에서 왔고, 5 년 후에 Java를 사용하는 것은 두 번째입니다.
실행중인 데이터베이스에서 zip 파일을 만들어 그 위치에 저장할 수 있는지 확실하지 않지만 검색을 통해이 코드를 작성했지만 현재 디렉터리를 반환하는 여러 메서드를 찾았지만 그중에는 디렉터리 i를 가리 킵니다. 원합니다 ... 그중 하나는 디버그에서 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();
}
}
내가 직접 응답에 쓰고 반환하기 때문에 생산이 아무것도하지 않는지 확실하지 않습니다 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();
}
}
백업은 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 백업 데이터베이스는 압축 할 수있는 파일 세트를 생성합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다