Preface
Something happened some time ago that made me laugh or cry. A project deployed on the Centos
server, because it needs Re-upload · Deployment
, so I executed the following command:
rm -rf /*
When I pressed Enter, I found lines of code flashing through the terminal, and suddenly I felt that things were not simple. , in desperation, I quickly interrupted the terminal with ctrl c
. After the interruption, I started uploading files through fpt
, but found that ftp
had no response. I panicked now. You won’t destroy the system!
Next I decided to restart
the server, but, emmm..., it couldn’t be started! It really destroyed the system! After asking the bosses, I heard that Alibaba Cloud
can be restored if snapshot
exists, but I have not saved the snapshot! Just GG, it doesn’t matter if the program is gone, but the database is gone.
At this time, I realized that I needed to make a scheduled task
to regularly back up the
database. Combined with the previously encapsulated Email
class, the backed up The database is sent to the mailbox.
Development and Deployment
Because my backend uses nodejs
, I will use nodejs
to write scheduled tasks here.
Installing dependencies
The node-schedule
dependency is needed to execute scheduled tasks, and the child_process
dependency is needed to execute the backup command.
npm i node-schedule child_process
Writing code
Create a new BackupDB.ts
file in the src/command
directory, and introduce dependencies in this file:
import schedule from "node-schedule"; import { spawn } from "child_process"; import fs from "fs";
Define a methodbackupDb
, all backup operations are within this method:
export const backupDb = () => {}
Use timestamp
in the method to define backupunique
File name, and Create stream
:
export const backupDb = () => { const dumpFileName = `${Math.round(Date.now() / 1000)}.dump.sql`; const writeStream = fs.createWriteStream(dumpFileName); }
Define the backup script in the method:
export const backupDb = () => { const dumpFileName = `${Math.round(Date.now() / 1000)}.dump.sql`; const writeStream = fs.createWriteStream(dumpFileName); const dump = spawn("mysqldump",[ "-u", "你的mysql账户名", "-p", "你的mysql账户密码", "所要备份的数据库名" ]) }
Next time execute the backup
command:
export const backupDb = () => { const dumpFileName = `${Math.round(Date.now() / 1000)}.dump.sql`; const writeStream = fs.createWriteStream(dumpFileName); const dump = spawn("mysqldump",[ "-u", "你的mysql账户名", "-p", "你的mysql账户密码", "所要备份的数据库名" ]) schedule.scheduleJob("0 0 1 * * *", function(){ dump.stdout.pipe(writeStream) .on("finish",() => { console.log("备份成功") }) .on("error",() => { console.log("备份失败") }) }) }
Of course, the hard-coded data here can also be controlled as function parameters. In addition, 0 0 1 * * *
means Backup at 1 am every day
, For the specific time format, please refer to the figure below, or the official document:
In the callback of a successful backup, call the Email
class to send the backup content to EMAIL
, if this is not the focus, I won’t write it for now.
Finally in the src/command/index.js
file Introduce the
backup method and call
:
import { backupDb } from "./BackupDB"; backupDb();
pm2 deployment
You need to install it globally first pm2
:
npm i pm2 -g
pm2
The deployment command format is: pm2 start [nodejs file] -- name [alias]
:
pm2 start ./src/command/index.js --name backupDb
After the deployment is completed, you can view it through the pm2 ls
command.
At this point, the database will be backed up
at 1:00 a.m.
every day and sent to email
.
The above is the detailed content of How to implement scheduled backup of MySQL in Node. For more information, please follow other related articles on the PHP Chinese website!

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools
