问题描述
我已经在我的C#项目中实现了Redis Cache.我只想知道如何重载 Get< T>
来接受超时值.我认为这将是为我的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可以自行处理到期.我的意思是,每个在其中添加要缓存的键的地方都应该添加一个到期时间,因此,每次获取该键时,如果该键已过期,则结果为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缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!