簡體   English   中英

將過期時間添加到 Redis 緩存

[英]Add Expiry to Redis Cache

我已經在我的 C# 項目中實現了 Redis 緩存。 我只想知道如何重載我的Get<T>以接受超時值。 我認為這將是向我的 redis 緩存提供程序添加到期時間的最佳方式。 這是我的代碼如下:

public async Task<T> GetAsync<T>(string key)
{
    return (await _cacheClient.Db0.GetAsync<T>(key).ConfigureAwait(false));
}
/// <summary>
/// Fetch item from cache
/// </summary>
/// <typeparam name="T">Return Type</typeparam>
/// <param name="key">Key identifier in cache</param>
/// <returns>Cached item</returns>
public T Get<T>(string key)
{
    return AsyncHelper.RunSync(() => _cacheClient.Db0.GetAsync<T>(key));

}

/// <summary>
/// Fetch from cache, else execute operation and cache
/// </summary>
/// <typeparam name="T">Return Type</typeparam>
/// <param name="key">Key identifier in cache</param>
/// <param name="method">Method to execute</param>
/// <param name="args">Method args</param>
/// <returns></returns>
public async Task<T> GetAsync<T>(string key, Delegate method, params object[] args)
{
    T result = default(T);

    try
    {
        if (await _cacheClient.Db0.ExistsAsync(key))
        {
            return await _cacheClient.Db0.GetAsync<T>(key);
        }
        else
        {
            result = ExecMethod<T>(method, args);
            await _cacheClient.Db0.AddAsync(key, result);
        }
    }
    catch (Exception ex)
    {
        _logHandler.LogError($"Error fetching cache for key:{key}", ex);
        result = ExecMethod<T>(method, args);
    }

    return result;
}
/// <summary>
/// Fetch from cache, else execute operation and cache
/// </summary>
/// <typeparam name="T">Return Type</typeparam>
/// <param name="key">Key identifier in cache</param>
/// <param name="method">Method to execute</param>
/// <param name="args">Method args</param>
/// <returns></returns>
public T Get<T>(string key, Delegate method, params object[] args)
{
    T result = default(T);

    try
    {

        if (AsyncHelper.RunSync(() => _cacheClient.Db0.ExistsAsync(key)))
        {
            result = AsyncHelper.RunSync(() => _cacheClient.Db0.GetAsync<T>(key));
        }
        else
        {
            result = ExecMethod<T>(method, args);
            var added = AsyncHelper.RunSync(() => _cacheClient.Db0.AddAsync(key, result));
        }
    }
    catch (Exception ex)
    {
        _logHandler.LogError($"Error fetching cache for key:{key}", ex);
        result = ExecMethod<T>(method, args);
    }

    return result;
}

這是更好地使用KeyExpire功能StackExchange ,讓Redis的可自行處理過期。 我的意思是,你添加一個鍵來緩存的每一個地方都應該添加一個過期時間,所以每次你獲取密鑰時,如果它過期了,結果是空的,你可以處理它。

代碼示例類似於:

cache.Add("Key","Value1");
cache.KeyExpire("Key", new TimeSpan(0, 0, 30));

或者

StringSetAsync("Key1", "Value1", new TimeSpan(0, 0, 30))

正如評論中所建議的那樣。 這是如何

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM