如何在Redis缓存中添加/更新/删除值

3

我对分布式缓存还很陌生,以下是我的代码,如果缓存中没有用户列表值,则从数据库表中将其存储在缓存中。

var cacheKey ="samplekey";

var userListdata = //contains list of users from a db table

var data = _distributedCache.GetString(cacheKey);
if (!string.IsNullOrEmpty(data))
{
    var tModel = JsonConvert.DeserializeObject<List<user>>(data);
    return new CommandActionResult<List<user>>(tModel, CommandActionStatus.NothingModified);
}
else
{
    var jsonData = JsonConvert.SerializeObject(userListdata);
    _distributedCache.SetString(cacheKey, jsonData);
    return new CommandActionResult<List<user>>(null, CommandActionStatus.NothingModified);
}

如果我需要向表中添加/删除/更新新用户,我该如何添加/更新/删除samplekey缓存键?


你正在使用哪种缓存?Redis吗? - user4851087
@NgôHùngPhúc 是的,redis。 - chikor.net
2个回答

0
在.NET Core中更新分布式缓存列表项时,请使用“Distributed Cache”库中提供的ListSetByIndexAsync函数,并可以通过IDistributedCache接口访问。

  await _cache.ListSetByIndexAsync(key,index, redisValue);
  • key 是缓存键
  • index 是要更新的索引位置
  • redisValue 是列表中要更新的项

要访问索引,请使用 IndexOf 函数。


0
你可以改变方法。将每个用户保存在redis缓存中的userListdata中,就像一个独特的keyValuePair一样。然后,您可以用这个进行插入/更新/删除操作。
// add the users to azure redis cache
foreach (var user in userListdata)
{
    _distributedCache.StringSet(user.Id, JsonConvert.SerializeObject(user));
}
// update/delete your records
var data = _distributedCache.GetString(cacheKey);
if (!string.IsNullOrEmpty(data)){
    _distributedCache.KeyDelete(cacheKey);
    _distributedCache.StringSet(cacheKey, newValues);
}
// else insert a new one...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接