redis 分布式锁(单机)

router.get('/lock', async (ctx, next) => {
  const resource = 'locks:account:11111';
  const ttl = 8000;
  const value = uuid.v1();
  const startTime = moment().format('YYYY-MM-DD HH:mm:ss');
  console.log('worker' + cluster.worker.id + ',PID:' + process.pid);
  let lock = null;
  while (!lock) {
    lock = await redis.set(resource, value, 'PX', ttl, 'NX');
    if (lock) {
      await sleep(800); //模拟处理业务
      const DelScript = `
    if redis.call("get",KEYS[1]) == ARGV[1] then
        return redis.call("del",KEYS[1])
    else
        return 0
    end
    `;
      const del = (key, val) =>
        new Promise((resolve, reject) => {
          redis.eval(DelScript, 1, key, val, (err, result) => {
            if (err) {
              console.log(err);
              reject(err);
              return;
            }
            resolve(result);
          });
        });
      const res = await del(resource, value);
      console.log('res', res);
      const endTime = moment().format('YYYY-MM-DD HH:mm:ss');
      ctx.body = `success:startTime: ${startTime};endTime:${endTime}`;
    } else {
      // console.log('等待10ms');
      await sleep(10); //等待10ms
    }
  }
});

 

posted @ 2020-06-09 17:38  不知不觉、  阅读(287)  评论(0编辑  收藏  举报