Skip to content

Instantly share code, notes, and snippets.

@nishanc
Created April 16, 2022 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nishanc/aee01e9fa889661fe355eeceaca0aa8e to your computer and use it in GitHub Desktop.
Save nishanc/aee01e9fa889661fe355eeceaca0aa8e to your computer and use it in GitHub Desktop.
public static class CacheHelper
{
public static async Task SetRecordAsync<T>(this IDistributedCache cache,
string recordId,
T data,
TimeSpan? absoluteExpireTime = null,
TimeSpan? slidingExpireTime = null)
{
var options = new DistributedCacheEntryOptions();
options.AbsoluteExpirationRelativeToNow = absoluteExpireTime ?? TimeSpan.FromSeconds(60);
options.SlidingExpiration = slidingExpireTime;
var jsonData = JsonSerializer.Serialize(data);
await cache.SetStringAsync(recordId, jsonData, options);
}
public static async Task<T?> GetRecordAsync<T>(this IDistributedCache cache,
string recordId)
{
var jsonData = await cache.GetStringAsync(recordId);
if (jsonData is null)
{
return default(T);
}
return JsonSerializer.Deserialize<T>(jsonData);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment