如何用Redis缓存实现自动刷新
How to implement auto-refresh with Redis cache
MemoryCache 有一个 Set 方法,可以让我指定一个委托,该委托在通过 CacheItemPolicy
参数从缓存中删除缓存条目之前调用。
这可以用于 auto refresh the cache 定期 auto refresh the cache 而无需使用 Hangfire 或其他一些任务运行器。
如何使用 StackExchange.Redis 在 .NET 中实现它?
我无法在 Redis command reference 中找到任何适合我目的的方法,我在网上找到的 ObjectCache
的所有实现都在它们的 NotSupportedException
中抛出一个 NotSupportedException
实施:
https://github.com/justinfinch/Redis-Object-Cache/blob/master/src/RedisObjectCache/RedisCache.cs
https://www.leadtools.com/help/sdk/v20/dh/to/azure-redis-cache-example.html
https://github.com/Azure/aspnet-redis-providers/pull/72/commits/2930ede272fe09abf930208dfe935c602c1bb510
Redis 中没有内置这样的东西。
但是,Redis 确实支持 keyspace notifications,它提供了一种注册 Expired
事件的方法。
您可以注册一个将对此类事件做出反应并刷新缓存的客户端。
另一种选择是在 expired
--> register(eventTypes=['exired'])
事件上使用 RedisGears and register,这样每次触发过期事件时,嵌入到 Redis 中运行的函数都会刷新数据.
缓存中的典型模式是调用缓存数据,当找不到时加载它。
public T Get<T>(string key)
{
T ret = GetFromRedis<T>(key); // I am not going to go into implementation of GetFromRedis for purpose of this question
if (ret == null)
{
// in the multi-server situation, this lock can be
// implemented as UPDATE record lock on DB transaction ***
lock(_loadLock)
{
ret = GetFromRedis<T>(key);
if (ret == null)
{
ret = DataProvider.Load<T>();
SetInRedis(key, ret);
}
}
}
return ret;
}
*** 对于 !!multiple!! 我不会过分强调那个锁!服务器。是的,您可能会在第一次加载时加载两次或更多次数据,但您的 redis SET
可以使用 When.NotExists
。这样,当多个线程尝试这样做时,实际缓存将不会被替换。因此,这是按需缓存与常量缓存的对比。例如,在大型应用程序中,有些部分未被使用。为什么要填充缓存?然后,用户开始点击零件,瞧!
MemoryCache 有一个 Set 方法,可以让我指定一个委托,该委托在通过 CacheItemPolicy
参数从缓存中删除缓存条目之前调用。
这可以用于 auto refresh the cache 定期 auto refresh the cache 而无需使用 Hangfire 或其他一些任务运行器。
如何使用 StackExchange.Redis 在 .NET 中实现它?
我无法在 Redis command reference 中找到任何适合我目的的方法,我在网上找到的 ObjectCache
的所有实现都在它们的 NotSupportedException
中抛出一个 NotSupportedException
实施:
https://github.com/justinfinch/Redis-Object-Cache/blob/master/src/RedisObjectCache/RedisCache.cs https://www.leadtools.com/help/sdk/v20/dh/to/azure-redis-cache-example.html https://github.com/Azure/aspnet-redis-providers/pull/72/commits/2930ede272fe09abf930208dfe935c602c1bb510
Redis 中没有内置这样的东西。
但是,Redis 确实支持 keyspace notifications,它提供了一种注册 Expired
事件的方法。
您可以注册一个将对此类事件做出反应并刷新缓存的客户端。
另一种选择是在 expired
--> register(eventTypes=['exired'])
事件上使用 RedisGears and register,这样每次触发过期事件时,嵌入到 Redis 中运行的函数都会刷新数据.
缓存中的典型模式是调用缓存数据,当找不到时加载它。
public T Get<T>(string key)
{
T ret = GetFromRedis<T>(key); // I am not going to go into implementation of GetFromRedis for purpose of this question
if (ret == null)
{
// in the multi-server situation, this lock can be
// implemented as UPDATE record lock on DB transaction ***
lock(_loadLock)
{
ret = GetFromRedis<T>(key);
if (ret == null)
{
ret = DataProvider.Load<T>();
SetInRedis(key, ret);
}
}
}
return ret;
}
*** 对于 !!multiple!! 我不会过分强调那个锁!服务器。是的,您可能会在第一次加载时加载两次或更多次数据,但您的 redis SET
可以使用 When.NotExists
。这样,当多个线程尝试这样做时,实际缓存将不会被替换。因此,这是按需缓存与常量缓存的对比。例如,在大型应用程序中,有些部分未被使用。为什么要填充缓存?然后,用户开始点击零件,瞧!