C# ServiceStack.Redis SetAll 过期
C# ServiceStack.Redis SetAll with expire
首先,link到图书馆:ServiceStack.Redis
现在,我正在研究一些通用缓存机制,目前支持 4 种方法:
放置、获取、PutMany、GetMany
问题是,每当我想插入大量记录时,我都没有添加过期的选项(对我来说可见),不像 Put - 我可以这样做。
代码非常直接:
public void PutMany(ICollection<T> items)
{
TimeSpan expiration = GetExpiration();
DateTime expire = DateTime.UtcNow.Add(expiration);
Dictionary<string, CachedItem<T>> dict = new Dictionary<string, CachedItem<T>>();
foreach (T item in items)
{
CachedItem<T> cacheItem = new CachedItem<T>(item, expire);
if (!dict.ContainsKey(cacheItem.Id))
dict.Add(cacheItem.Id, cacheItem);
}
// Store item in cache
_client.SetAll(dict);
}
模型CachedItem<T>
是我的,把它想象成某种物体。
如您所见,我没有设置到期时间的选项。
有没有办法(除了使用 _client.Set()
将它们 1 对 1 插入)来实现这个?
TIA。
P.S
我知道我可以将所有记录存储在列表或散列中,我不希望所有记录都有一个单一的到期日期(错误,并且一旦到期就会导致非常严重的性能问题)
Redis 没有任何命令可以让您set an expiry with a bulk insert nor does any of its Expire commands允许您将到期时间应用到多个键。
为避免 N+1 操作,您需要 queue multiple SET commands in a Redis Transaction or pipeline,为每个条目分别设置到期时间,例如:
using (var trans = Redis.CreateTransaction())
{
foreach (var entry in dict)
{
trans.QueueCommand(r => r.SetValue(entry.Key, entry.Value, expireIn));
}
trans.Commit();
}
其中 ServiceStack.Redis 仍将在 bulk Redis transaction 中发送多个 SET 操作。
首先,link到图书馆:ServiceStack.Redis
现在,我正在研究一些通用缓存机制,目前支持 4 种方法:
放置、获取、PutMany、GetMany
问题是,每当我想插入大量记录时,我都没有添加过期的选项(对我来说可见),不像 Put - 我可以这样做。
代码非常直接:
public void PutMany(ICollection<T> items)
{
TimeSpan expiration = GetExpiration();
DateTime expire = DateTime.UtcNow.Add(expiration);
Dictionary<string, CachedItem<T>> dict = new Dictionary<string, CachedItem<T>>();
foreach (T item in items)
{
CachedItem<T> cacheItem = new CachedItem<T>(item, expire);
if (!dict.ContainsKey(cacheItem.Id))
dict.Add(cacheItem.Id, cacheItem);
}
// Store item in cache
_client.SetAll(dict);
}
模型CachedItem<T>
是我的,把它想象成某种物体。
如您所见,我没有设置到期时间的选项。
有没有办法(除了使用 _client.Set()
将它们 1 对 1 插入)来实现这个?
TIA。
P.S
我知道我可以将所有记录存储在列表或散列中,我不希望所有记录都有一个单一的到期日期(错误,并且一旦到期就会导致非常严重的性能问题)
Redis 没有任何命令可以让您set an expiry with a bulk insert nor does any of its Expire commands允许您将到期时间应用到多个键。
为避免 N+1 操作,您需要 queue multiple SET commands in a Redis Transaction or pipeline,为每个条目分别设置到期时间,例如:
using (var trans = Redis.CreateTransaction())
{
foreach (var entry in dict)
{
trans.QueueCommand(r => r.SetValue(entry.Key, entry.Value, expireIn));
}
trans.Commit();
}
其中 ServiceStack.Redis 仍将在 bulk Redis transaction 中发送多个 SET 操作。