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

标签 c# redis .net-core

我是分布式缓存的新手,我有下面的代码,如果不存在,它将数据库表中的用户列表值存储在缓存中。

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/

相关文章:

c# - FFMPEG缓存如何配置和获取缓存文件名

c# - Xamarin UICollectionViewController 每行显示 2 个单元格?

c# - 在哪些情况下 JsonConvert.DeserializeObject<T> 实际上返回 null?

c# - 外部引用 (DLL) 中的后台 Worker 锁定主线程

c# - 什么时候需要在 EF 的 DbContext 中指定 DbSet?

python - Redis pubsub 给出错误的结果

python - 在redis中存储带有过期前缀的键

laravel - php redis 和 laravel 中的 redis 有什么区别?

c# - 是否可以从 .NET 核心在 linux 平台上调用共享库 (.so)?

visual-studio-code - dotnet restore 给出 401, "Unable to load the service index"