Add Expiry to Redis Cache

て烟熏妆下的殇ゞ 提交于 2021-02-17 05:59:06

问题


I have implemented Redis Cache in my C# project. I would just like to know how i can overload my Get<T> to also accept a timeout value. I figured this would be the best way to add an expiry to my redis cache provider. Here is my code Below:

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;
}

回答1:


It is better to use KeyExpire function in StackExchange, so that Redis can handle the expiration by itself. I mean every where you add a key to cache it should be added with an expiration, so every time you fetch the key, if it is expired, the result is null and you can handle it.

code example is something like:

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

or

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

as suggested in comments. Here is how.



来源:https://stackoverflow.com/questions/60927540/add-expiry-to-redis-cache

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!