StackExchange.Redis - LockTake / LockRelease Usage

前端 未结 2 964
再見小時候
再見小時候 2020-12-04 15:59

I am using Redis with StackExchange.Redis. I have multiple threads that will at some point access and edit the value of the same key, so I need to synchronize the manipulati

2条回答
  •  借酒劲吻你
    2020-12-04 16:28

    There are 3 parts to a lock:

    • the key (the unique name of the lock in the database)
    • the value (a caller-defined token which can be used both to indicate who "owns" the lock, and to check that releasing and extending the lock is being done correctly)
    • the duration (a lock intentionally is a finite duration thing)

    If no other value comes to mind, a guid might make a suitable "value". We tend to use the machine-name (or a munged version of the machine name if multiple processes could be competing on the same machine).

    Also, note that taking a lock is speculative, not blocking. It is entirely possible that you fail to obtain the lock, and hence you may need to test for this and perhaps add some retry logic.

    A typical example might be:

    RedisValue token = Environment.MachineName;
    if(db.LockTake(key, token, duration)) {
        try {
            // you have the lock do work
        } finally {
            db.LockRelease(key, token);
        }
    }
    

    Note that if the work is lengthy (a loop, in particular), you may want to add some occasional LockExtend calls in the middle - again remembering to check for success (in case it timed out).

    Note also that all individual redis commands are atomic, so you don't need to worry about two discreet operations competing. For more complexing multi-operation units, transactions and scripting are options.

提交回复
热议问题