尝试重新锁定Redlock Node.js中的资源错误

时间:2018-11-15 12:20:54

标签: node.js ioredis redlock.net

我练习redis和redlock,并编写了一些函数来处理例如银行的基本交易。我有2个帐户,我想在这2个帐户之间转移资金。为了解决同步问题,我使用了redlock模块。这是我的代码,但出现错误提示:

UnhandledPromiseRejectionWarning: LockError: Exceeded 10 attempts to lock the resource "bahrami".

这是我的代码:

const redis = require('./redis')
const readline = require('readline')
var Redlock = require('redlock');

var redlock = new Redlock(
    // you should have one client for each independent redis node
    // or cluster
    [redis],
    {
        // the expected clock drift; for more details
        // see http://redis.io/topics/distlock
        driftFactor: 0.01, // time in ms

        // the max number of times Redlock will attempt
        // to lock a resource before erroring
        retryCount:  10,

        // the time in ms between attempts
        retryDelay:  200, // time in ms

        // the max time in ms randomly added to retries
        // to improve performance under high contention
        // see https://www.awsarchitectureblog.com/2015/03/backoff.html
        retryJitter:  200 // time in ms
    }
);

const  ttl = 1000;

const transferMoney = async () => {
    const sourceAccount = await getInput('enter sourceAccount');
    const destinationAccount = await getInput('enter destinationAccount');
    const money = await getInput ('enter amount of money ')

    const sourceLock = await redlock.lock(sourceAccount, ttl)

    const sourceAccountAmount = await redis.get(sourceAccount)

    const destLock = await redlock.lock(destinationAccount, ttl)

    const destinationAccountAmount = await redis.get(destinationAccount)


    if (sourceAccountAmount >= money){
        await redis.set(sourceAccount, sourceAccountAmount - money)
        const sum = parseInt(destinationAccountAmount) + parseInt(money)
        await redis.set(destinationAccount, sum)

    }
    else{
        console.log('your money does not enough!')
    }

    const tr = await redis.lpush(`transaction:s:${sourceAccount}:d:${destinationAccount}`, JSON.stringify({Amount}))
    console.log(tr)

    await sourceLock.unlock()
    await destLock.unlock()
}

0 个答案:

没有答案