redisstackexchange.redisappfabric-cache

AppFabric Cache to Redis - equivalent of the GetAndLock method?


I'm currently moving from Microsoft AppFabric Cache to Redis on Windows. In the past, I was using the GetAndLock method of AppFabric. Is there a method in Redis to do a GetAndLock ? (I'm using the StackExchange.Redis.StrongName nugget lib).

Thanks.


Solution

  • StackExchange.Redis has some locking methods, if you're trying to protect a critical code section from being run more than once at a time.

    if (connectionMultiplexer.GetDatabase().LockTake(key, token, duration))
    {
        try
        {
            // do stuff
        }
        finally
        {
            connectionMultiplexer.GetDatabase().LockRelease(key, token);
        }
    }
    

    There are also LockExtend and LockQuery methods.

    See https://stackoverflow.com/a/25138164/2497886 for some more detailed information.

    It's also worth having a look at the redis documentation on distributed locks - http://redis.io/topics/distlock.

    The RedLock.net library implements the distlock algorithm, and supports things like blocking/retrying to obtain a lock and automatic lock extension. (disclaimer: I am the author of the library)