我是分布式缓存的新手,我有下面的代码,如果不存在,它将数据库表中的用户列表值存储在缓存中。
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 缓存键?
最佳答案
您可以更改方法。将每个用户保存在 userListdata 中,就像在 redis 缓存中保存唯一的 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...
关于c# - 如何在 Redis 缓存中添加/更新/删除值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51369828/