将过期时间添加到 Redis 缓存 [英] Add Expiry to Redis Cache

查看:36
本文介绍了将过期时间添加到 Redis 缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在我的 C# 项目中实现了 Redis 缓存.我只想知道如何重载我的 Get 以同时接受超时值.我认为这将是向我的 redis 缓存提供程序添加到期时间的最佳方式.这是我的代码如下:

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

推荐答案

最好在StackExchange中使用KeyExpire函数,这样Redis就可以自己处理过期了.我的意思是每一个你添加一个key来缓存的地方都应该添加一个过期时间,所以每次你获取key时,如果它过期了,结果就是null,你可以处理它.

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.

代码示例类似于:

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

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

如评论中所建议.这是方法.

这篇关于将过期时间添加到 Redis 缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆