34

StackExchange.Redis で Redis を使用しています。ある時点で同じキーの値にアクセスして編集する複数のスレッドがあるため、データの操作を同期する必要があります。

利用可能な関数を見ると、TakeLock と ReleaseLock の 2 つの関数があることがわかります。ただし、これらの関数は、ロックされると予想される単一のキーではなく、キーと値の両方のパラメーターを取ります。Intellisene のドキュメントと GitHub のソースでは、LockTake 関数と LockRelease 関数の使用方法や、キーと値のパラメーターに何を渡すかについて説明していません。

Q: StackExchange.Redis での LockTake と LockRelease の正しい使用法は何ですか?

私がやろうとしていることの疑似コードの例:

//Add Items Before Parallel Execution
redis.StringSet("myJSONKey", myJSON);

//Parallel Execution
Parallel.For(0, 100, i =>
    {
        //Some work here
        //....

        //Lock
        redis.LockTake("myJSONKey");

        //Manipulate
        var myJSONObject = redis.StringGet("myJSONKey");
        myJSONObject.Total++;
        Console.WriteLine(myJSONObject.Total);
        redis.StringSet("myJSONKey", myNewJSON);

        //Unlock
        redis.LockRelease("myJSONKey");

        //More work here
        //...
    });
4

2 に答える 2

59

ロックには 3 つの部分があります。

  • キー (データベース内のロックの一意の名前)
  • 値 (誰がロックを「所有」しているかを示すため、およびロックの解放と拡張が正しく行われていることを確認するために使用できる呼び出し元定義のトークン)
  • 期間(ロックは意図的に有限期間のものです)

他の値が思い浮かばない場合は、GUID が適切な「値」を作成する可能性があります。machine-name (または、複数のプロセスが同じマシン上で競合する可能性がある場合は、変更されたバージョンのマシン名) を使用する傾向があります。

また、ロックの取得は投機的であり、ブロッキングではないことに注意してください。ロックの取得に失敗する可能性は十分にあるため、これをテストし、再試行ロジックを追加する必要がある場合があります。

典型的な例は次のとおりです。

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

作業が長い場合 (特にループ)、途中でいくつかの呼び出しを追加したい場合があることに注意してくださいLockExtend- ここでも成功を確認することを忘れないでください (タイムアウトの場合)。

また、個々の redis コマンドはすべてアトミックであるため、2 つの個別の操作が競合することを心配する必要はありません。より複雑な複数操作ユニットの場合、トランザクションスクリプトはオプションです。

于 2014-08-05T11:53:12.507 に答える
5

lock->get->modify (必要な場合)->unlock アクションのコメント付きのコードの一部があります。

    public static T GetCachedAndModifyWithLock<T>(string key, Func<T> retrieveDataFunc, TimeSpan timeExpiration, Func<T, bool> modifyEntityFunc,
       TimeSpan? lockTimeout = null, bool isSlidingExpiration=false) where T : class
    {
        
        int lockCounter = 0;//for logging in case when too many locks per key
        Exception logException = null;

        var cache = Connection.GetDatabase();
        var lockToken = Guid.NewGuid().ToString(); //unique token for current part of code
        var lockName = key + "_lock"; //unique lock name. key-relative.
        T tResult = null;
        
        while ( lockCounter < 20)
        {
            //check for access to cache object, trying to lock it
            if (!cache.LockTake(lockName, lockToken, lockTimeout ?? TimeSpan.FromSeconds(10)))
            {
                lockCounter++;
                Thread.Sleep(100); //sleep for 100 milliseconds for next lock try. you can play with that
                continue;
            }

            try
            {
                RedisValue result = RedisValue.Null;

                if (isSlidingExpiration)
                {
                    //in case of sliding expiration - get object with expiry time
                    var exp = cache.StringGetWithExpiry(key);
                    
                    //check ttl.
                    if (exp.Expiry.HasValue && exp.Expiry.Value.TotalSeconds >= 0)
                    {
                        //get only if not expired
                        result = exp.Value;
                    }
                }
                else //in absolute expiration case simply get
                {
                    result = cache.StringGet(key);
                }

                //"REDIS_NULL" is for cases when our retrieveDataFunc function returning null (we cannot store null in redis, but can store pre-defined string :) )
                if (result.HasValue && result == "REDIS_NULL") return null;
                //in case when cache is epmty
                if (!result.HasValue)
                {
                    //retrieving data from caller function (from db from example)
                    tResult = retrieveDataFunc();

                    if (tResult != null)
                    {
                        //trying to modify that entity. if caller modifyEntityFunc returns true, it means that caller wants to resave modified entity.
                        if (modifyEntityFunc(tResult))
                        {
                            //json serialization
                            var json = JsonConvert.SerializeObject(tResult);
                            cache.StringSet(key, json, timeExpiration);
                        }
                    }
                    else
                    {
                        //save pre-defined string in case if source-value is null.
                        cache.StringSet(key, "REDIS_NULL", timeExpiration);
                    }
                }
                else
                {
                    //retrieve from cache and serialize to required object
                    tResult = JsonConvert.DeserializeObject<T>(result);
                    //trying to modify
                    if (modifyEntityFunc(tResult))
                    {
                        //and save if required
                        var json = JsonConvert.SerializeObject(tResult);
                        cache.StringSet(key, json,  timeExpiration);
                    }
                }

                //refresh exiration in case of sliding expiration flag
                if(isSlidingExpiration)
                    cache.KeyExpire(key, timeExpiration);
            }
            catch (Exception ex)
            {
                logException = ex;
            }
            finally
            {                    
                cache.LockRelease(lockName, lockToken);
            }
            break;
        }

        if (lockCounter >= 20 || logException!=null)
        {
            //log it
        }

        return tResult;
    }

と使用法:

public class User
{
    public int ViewCount { get; set; }
}

var cachedAndModifiedItem = GetCachedAndModifyWithLock<User>( 
        "MyAwesomeKey", //your redis key
        () => // callback to get data from source in case if redis's store is empty
        {
            //return from db or kind of that
            return new User() { ViewCount = 0 };
        }, 
        TimeSpan.FromMinutes(10), //object expiration time to pass in Redis
        user=> //modify object callback. return true if you need to save it back to redis
        {
            if (user.ViewCount< 3)
            {
                user.ViewCount++;
                return true; //save it to cache
            }
            return false; //do not update it in cache
        },
        TimeSpan.FromSeconds(10), //lock redis timeout. if you will have race condition situation - it will be locked for 10 seconds and wait "get_from_db"/redis read/modify operations done.
        true //is expiration should be sliding.
        );

そのコードは改善される可能性があります (たとえば、キャッシュへの呼び出し回数を減らすためにトランザクションを追加することができます) が、お役に立てば幸いです。

于 2015-09-29T19:42:55.353 に答える