I have api project in .net core. When I was restaring azure service for this api, IDistributedCache is cleared. After restarting, while fetching data from GetSubscriptionRecord() method it returns null.
My startup.cs contains
services.AddDistributedMemoryCache();
services.AddSingleton<SubscriptionStore>();
and
public class SubscriptionStore
{
private readonly IDistributedCache _cache;
public SubscriptionStore(IDistributedCache memoryCache)
{
_cache = memoryCache ?? throw new ArgumentException(nameof(memoryCache));
}
/// <summary>
/// Add a subscription record to the store
/// </summary>
/// <param name="record">The subscription to add</param>
public void SaveSubscriptionRecord(SubscriptionRecord record)
{
var options = new DistributedCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromHours(10));
_cache.SetAsync(record.Id, ToByteArray<SubscriptionRecord>(record), options);
}
/// <summary>
/// Get a subscription record
/// </summary>
/// <param name="subscriptionId">The subscription ID</param>
/// <returns>The subscription record if found, null if not</returns>
public async Task<SubscriptionRecord> GetSubscriptionRecord(string subscriptionId)
{
var record = await _cache.GetAsync(subscriptionId);
return FromByteArray<SubscriptionRecord>(record);
}
}
CodePudding user response:
Looks like you are using in-memory cache which is stored at application memory. It means that is would be destroyed after app is stopped/restarted.
See documentation link for details
The Distributed Memory Cache (AddDistributedMemoryCache) is a framework-provided implementation of IDistributedCache that stores items in memory. The Distributed Memory Cache isn't an actual distributed cache. Cached items are stored by the app instance on the server where the app is running.
You can try to configure some remote cache storage like Redis, SQL Server or NCache cluster
