首先,链接到库:ServiceStack.Redis
现在,我正在研究一些通用的缓存机制,该机制目前支持4种方法:
放置,获取,放置很多,获取很多
问题是,每当我要插入大量记录时,我都没有选择权(对我可见)添加到期日,这与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()
一对一地插入它们)?TIA。
P.S
我知道我可以将所有记录存储在列表或哈希中,我不希望所有记录都具有单个到期日期(错误,并且一旦到期就会引起非常严重的性能问题)
最佳答案
Redis没有任何允许您使用set an expiry with a bulk insert的命令,也没有任何Expire commands允许您将到期时间应用于多个键。
为了避免进行N + 1操作,您需要queue multiple SET commands in a Redis Transaction或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操作。
关于c# - C#ServiceStack.Redis SetAll与到期,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43893858/