我已经在我的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;
}
1条答案
按热度按时间py49o6xq1#
最好使用
KeyExpire
中的函数StackExchange
,这样redis就可以自己处理到期。我的意思是,每次向缓存中添加密钥时,都应该添加一个过期的密钥,因此每次获取密钥时,如果密钥过期,则结果为null,您可以处理它。代码示例如下:
或者
正如评论中所建议的那样。这里是如何。