两个node服务共同修改一个计数文件,互相监控服务是否停止

 

node服务A:

const fs = require('fs')

let timer
let startValue


//监控
const toolsMonitor = async (req, res) => {
  const monitorFilePath = '/temp/log/monitor.json'
  clearInterval(timer)
  fs.readFile(monitorFilePath, 'utf-8', function (err, data) {
    if (err) {
      console.log(err)
    } else {
      let dataObj = eval('(' + data + ')')
      startValue = dataObj.count
    }
  })  
  let isAlert = false
  timer = setInterval(() => {
    fs.readFile(monitorFilePath, 'utf-8', function (err, data) {
      if (err) {
        console.log(err)
      } else {
        let dataObj = eval('(' + data + ')')
        dataObj.count = dataObj.count + 1
        console.log(dataObj.count, startValue)
        if (dataObj.count - startValue > 5 && isAlert === false) {
          console.log('报警')
          isAlert = true
        }
        fs.writeFile(
          monitorFilePath,
          JSON.stringify(dataObj, null, 2),
          { encoding: 'utf8' },
          (err) => {
            if (err) {
              console.log(err)
            }
          }
        )
      }
    })
  }, 1000)

  res.send({
    code: 200,
    data: {},
    message: '监控成功'
  })
}

node服务B:

const fs = require('fs')

let timer
let startValue


//监控
const toolsMonitor = async (req, res) => {
  const monitorFilePath = '/temp/log/monitor.json'
  clearInterval(timer)
  fs.readFile(monitorFilePath, 'utf-8', function (err, data) {
    if (err) {
      console.log(err)
    } else {
      let dataObj = eval('(' + data + ')')
      startValue = dataObj.count
    }
  })  
  let isAlert = false
  timer = setInterval(() => {
    fs.readFile(monitorFilePath, 'utf-8', function (err, data) {
      if (err) {
        console.log(err)
      } else {
        let dataObj = eval('(' + data + ')')
        dataObj.count = dataObj.count - 1
        console.log(dataObj.count, startValue)
        if (dataObj.count - startValue > 5 && isAlert === false) {
          console.log('报警')
          isAlert = true
        }
        fs.writeFile(
          monitorFilePath,
          JSON.stringify(dataObj, null, 2),
          { encoding: 'utf8' },
          (err) => {
            if (err) {
              console.log(err)
            }
          }
        )
      }
    })
  }, 1000)

  res.send({
    code: 200,
    data: {},
    message: '监控成功'
  })
}

monitor.json:

{
  "count": 0
}

猜你喜欢

转载自blog.csdn.net/xutongbao/article/details/126177861
今日推荐