搜索
首页数据库mysql教程Node定时备份MySQL怎么实现

Node定时备份MySQL怎么实现

Jun 02, 2023 pm 10:58 PM
mysqlnode

    前言

    前段时间发生了一件令我哭笑不得的事,部署在 Centos 服务器上的项目,因为需要重新上传· 部署,所以我执行了下面一段命令:

    rm -rf /*

    当我按下回车之后,发现终端闪过的一行行代码,突然感觉事情并不简单,情急之下,赶紧 ctrl c 中断终端,中断之后,便开始通过 fpt 上传文件,却发现 ftp 毫无反应,这下慌了,不会把系统给干没了吧!

    接下来我决定 重启 服务器,可是,emmm...,启动不了了!真的把系统给干没了!询问大佬们之后,听说 阿里云 如果存在 快照,则可以恢复,可是我并没有保存过快照!直接GG,程序没了倒无所谓,可是 数据库没了

    这时我意识到,需要做个 定时任务,定时 备份 数据库,结合之前封装的 Email 类,将备份的数据库发送至邮箱。

    开发部署

    因为我后端使用的是 nodejs,这里就使用 nodejs 编写定时任务吧。

    安装依赖

    这里需要 node-schedule 依赖来执行定时任务,需要 child_process 依赖来执行备份命令。

    npm i node-schedule child_process

    编写代码

    src/command 目录下新建一个 BackupDB.ts 文件,在此文件中引入依赖:

    import schedule from "node-schedule";
    import { spawn } from "child_process";
    import fs from "fs";

    定义一个方法 backupDb ,所有的备份操作都在此方法内:

    export const backupDb = () => {}

    在方法内使用 时间戳 定义备份 唯一 文件名,并 创建流

    export const backupDb = () => {
      const dumpFileName = `${Math.round(Date.now() / 1000)}.dump.sql`;
      const writeStream = fs.createWriteStream(dumpFileName);
    }

    在方法内定义备份脚本:

    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账户密码",
        "所要备份的数据库名"
      ])
    }

    接下来定时 执行备份 命令:

    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("备份失败")
          })
      })
    }

    当然这里写死的数据还可以作为函数参数可进行控制,另外这里的 0 0 1 * * * 表示 每天凌晨1点 备份,具体时间格式可参考下图,或官方文档:

    Node定时备份MySQL怎么实现

    在备份成功的回调中,调用 Email 类将备份内容发送至 邮箱,这里不作为重点就暂且不写。

    最后在 src/command/index.js 文件中 引入 备份方法并 调用

    import { backupDb } from "./BackupDB";
    
    backupDb();

    pm2部署

    这里需要先全局安装 pm2

    npm i pm2 -g

    pm2 部署的命令格式为:pm2 start [nodejs文件] --name [别名]

    pm2 start ./src/command/index.js --name backupDb

    部署完成之后,可以通过 pm2 ls 命令查看。

    至此,将在 每天凌晨1点 对数据库进行 备份,并发送至 邮箱

    以上是Node定时备份MySQL怎么实现的详细内容。更多信息请关注PHP中文网其他相关文章!

    声明
    本文转载于:亿速云。如有侵权,请联系admin@php.cn删除
    在MySQL中使用视图的局限性是什么?在MySQL中使用视图的局限性是什么?May 14, 2025 am 12:10 AM

    mysqlviewshavelimitations:1)他们不使用Supportallsqloperations,限制DatamanipulationThroughViewSwithJoinSorsubqueries.2)他们canimpactperformance,尤其是withcomplexcomplexclexeriesorlargedatasets.3)

    确保您的MySQL数据库:添加用户并授予特权确保您的MySQL数据库:添加用户并授予特权May 14, 2025 am 12:09 AM

    porthusermanagementInmysqliscialforenhancingsEcurityAndsingsmenting效率databaseoperation.1)usecReateusertoAddusers,指定connectionsourcewith@'localhost'or@'%'。

    哪些因素会影响我可以在MySQL中使用的触发器数量?哪些因素会影响我可以在MySQL中使用的触发器数量?May 14, 2025 am 12:08 AM

    mysqldoes notimposeahardlimitontriggers,butacticalfactorsdeterminetheireffactective:1)serverConfiguration impactactStriggerGermanagement; 2)复杂的TriggerSincreaseSySystemsystem load; 3)largertablesslowtriggerperfermance; 4)highConconcConcrencerCancancancancanceTigrignecentign; 5); 5)

    mysql:存储斑点安全吗?mysql:存储斑点安全吗?May 14, 2025 am 12:07 AM

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

    mySQL:通过PHP Web界面添加用户mySQL:通过PHP Web界面添加用户May 14, 2025 am 12:04 AM

    通过PHP网页界面添加MySQL用户可以使用MySQLi扩展。步骤如下:1.连接MySQL数据库,使用MySQLi扩展。2.创建用户,使用CREATEUSER语句,并使用PASSWORD()函数加密密码。3.防止SQL注入,使用mysqli_real_escape_string()函数处理用户输入。4.为新用户分配权限,使用GRANT语句。

    mysql:blob和其他无-SQL存储,有什么区别?mysql:blob和其他无-SQL存储,有什么区别?May 13, 2025 am 12:14 AM

    mysql'sblobissuitableForStoringBinaryDataWithInareLationalDatabase,而alenosqloptionslikemongodb,redis和calablesolutionsoluntionsoluntionsoluntionsolundortionsolunsolunsstructureddata.blobobobsimplobissimplobisslowderperformandperformanceperformancewithlararengelitiate;

    mySQL添加用户:语法,选项和安全性最佳实践mySQL添加用户:语法,选项和安全性最佳实践May 13, 2025 am 12:12 AM

    toaddauserinmysql,使用:createUser'username'@'host'Indessify'password'; there'showtodoitsecurely:1)choosethehostcarecarefullytocon trolaccess.2)setResourcelimitswithoptionslikemax_queries_per_hour.3)usestrong,iniquepasswords.4)Enforcessl/tlsconnectionswith

    MySQL:如何避免字符串数据类型常见错误?MySQL:如何避免字符串数据类型常见错误?May 13, 2025 am 12:09 AM

    toAvoidCommonMistakeswithStringDatatatPesInMysQl,CloseStringTypenuances,chosethirtightType,andManageEngencodingAndCollat​​ionsEttingsefectery.1)usecharforfixed lengengters lengengtings,varchar forbariaible lengength,varchariable length,andtext/blobforlabforlargerdata.2 seterters seterters seterters seterters

    See all articles

    热AI工具

    Undresser.AI Undress

    Undresser.AI Undress

    人工智能驱动的应用程序,用于创建逼真的裸体照片

    AI Clothes Remover

    AI Clothes Remover

    用于从照片中去除衣服的在线人工智能工具。

    Undress AI Tool

    Undress AI Tool

    免费脱衣服图片

    Clothoff.io

    Clothoff.io

    AI脱衣机

    Video Face Swap

    Video Face Swap

    使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

    热门文章

    热工具

    SublimeText3 英文版

    SublimeText3 英文版

    推荐:为Win版本,支持代码提示!

    PhpStorm Mac 版本

    PhpStorm Mac 版本

    最新(2018.2.1 )专业的PHP集成开发工具

    适用于 Eclipse 的 SAP NetWeaver 服务器适配器

    适用于 Eclipse 的 SAP NetWeaver 服务器适配器

    将Eclipse与SAP NetWeaver应用服务器集成。

    安全考试浏览器

    安全考试浏览器

    Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

    WebStorm Mac版

    WebStorm Mac版

    好用的JavaScript开发工具