'Clearing cache in Azure Function app and c#?
I'm using Azure Functions App and c# for coding. I want to clear the cache every 10 minutes for example, if there is a way to do that in the code ?
Solution 1:[1]
Please check if below references can give an idea.
Manage data expiration in a cache
In most cases, data that's held in a cache is a copy of data that's held in the original data store. The data in the original data store might change after it was cached, causing the cached data to become stale. Many caching systems enable you to configure the cache to expire data and reduce the period for which data may be out of date.
MemoryCache class in C#
This feature hasCache Eviction policies. The values will be present in the memoryCache as long the Cache Eviction time is not expired.When expired ,the cache will be cleared /removed and again application must get new values and start storing from original value i.e;populate the dictionary by checking the count.
You can set a default expiration policy when you configure the cache i.e the Cache Eviction time .
CacheItemPolicy can be used to add cache expiration time, change monitors, update callback etc.Here is simple example of CachItemPolicy object, which Absolute Expiration duration.
public static class Function1
{
public static MemoryCache accessTokenCache = new MemoryCache("accessToken");
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
// accessTokenCache.Add("123", "123", new CacheItemPolicy() { Priority = CacheItemPriority.Default
ObjectCache cache = MemoryCache.Default;
var cacheItemPolicy = new CacheItemPolicy { AbsoluteExpiration =
DateTimeOffset.Now.AddSeconds(60.0), };
cache.Add("CacheName3", "Expires In A Minute", cacheItemPolicy);
// We can remove any cache key-value object, using it's key and .Remove() method
cache.Remove("CacheName");
});
return new OkObjectResult("");
}
}
Another example that can be used in the function:
static MemoryCache memoryCacheTaxRates= new MemoryCache("cachename");
if (memoryCachecachename.GetCount() == 0)
{
RefreshCache(); //Get the values if nothing is in dictionary
}
//other code
RefreshCache()
{
memoryCachecachename.Set("sourceKey", "targetKey", DateTimeOffset.Now.AddMinutes(Double.Parse(Environment.GetEnvironmentVariable("CacheEvictionTimeInMinutes"))));
}
You can check even by using redis cache
but from the pricing perspective, it can cost more.
References:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | kavyasaraboju-MT |