Add RemoveAsync cache

This commit is contained in:
Haiping Chen 2024-09-26 17:22:06 -05:00
parent 0d78a3996a
commit ebeccad542
4 changed files with 34 additions and 1 deletions

View file

@ -5,4 +5,5 @@ public interface ICacheService
Task<T?> GetAsync<T>(string key);
Task<object> GetAsync(string key, Type type);
Task SetAsync<T>(string key, T value, TimeSpan? expiry);
Task RemoveAsync(string key);
}

View file

@ -31,7 +31,13 @@ public class SharpCacheAttribute : MoAttribute
var value = cache.GetAsync(key, context.TaskReturnType).Result;
if (value != null)
{
context.ReplaceReturnValue(this, value);
// check if the cache is out of date
var isOutOfDate = IsOutOfDate(context, value).Result;
if (!isOutOfDate)
{
context.ReplaceReturnValue(this, value);
}
}
}
@ -58,6 +64,11 @@ public class SharpCacheAttribute : MoAttribute
}
}
public virtual Task<bool> IsOutOfDate(MethodContext context, object value)
{
return Task.FromResult(false);
}
private string GetCacheKey(SharpCacheSettings settings, MethodContext context)
{
var key = settings.Prefix + "-" + context.Method.Name;

View file

@ -32,4 +32,9 @@ public class MemoryCacheService : ICacheService
AbsoluteExpirationRelativeToNow = expiry
});
}
public async Task RemoveAsync(string key)
{
_cache.Remove(key);
}
}

View file

@ -76,4 +76,20 @@ public class RedisCacheService : ICacheService
var db = redis.GetDatabase();
await db.StringSetAsync(key, JsonConvert.SerializeObject(value), expiry);
}
public async Task RemoveAsync(string key)
{
if (string.IsNullOrEmpty(_settings.Redis))
{
return;
}
if (redis == null)
{
redis = ConnectionMultiplexer.Connect(_settings.Redis);
}
var db = redis.GetDatabase();
await db.KeyDeleteAsync(key);
}
}