Skip to content

Using String version

Jon P Smith edited this page Oct 14, 2022 · 5 revisions

The primary FileStore distributed cache version is known as String because the value part of the cache entry of type string. The ` DistributedFileStoreCacheString is used by all the other FileStore cache version because the cache is stored as a json string.

The String FileStore cache provides a similar set of methods that the IDistributedCache interface with the following differences:

  • The value type is string, while the IDistributedCache interface has a value type of byte[]
  • It adds some extra features (see later)
  • It does not supports IDistributedCache’s SlidingExpiration feature for performance reasons.

The set of methods available in the String FileStore cache version are:

Standard IDistributedCache methods

Type Method names
Read a cache entry Get(string key) / GetAsync(string key)
Create/Update a cache entry Set(string key, string value,...) / SetAsync(string key, string value,...)
Delete a cache entry Remove(string key) / RemoveAsync(string key, ...)

NOTE: That the String FileStore cache version doesn't contain the Refresh / RefreshAsync methods.

Extra FileStore cache methods

Type Method names
Set many entries in one go SetMany(List<KeyValuePair<string, string>> manyEntries...)
SetManyAsync(List<KeyValuePair<string, string>> manyEntries,...)
Get ALL cache entries GetAllKeyValues / GetAllKeyValuesAsync(...)
Clear all the cache values ClearAll
Clear all, then add entries ClearAll(List<KeyValuePair<string, string>> manyEntries...)

NOTE: The SetMany / SetManyAsync methods can add multiple entries almost as quickly as a single Set / SetAsync. So, if you have multiple entries to add, then use the SetMany / SetManyAsync methods for better performance.

Example of using the FileStore cache String version

Once you have registered the FileStore cache (see Registering FileStore Cache) setting the WhichVersion to FileStoreCacheVersions.String then the String service is registered against the IDistributedFileStoreCacheString interface as a singleton. This example shows two methods from String FileStore distributed cache.

public class HomeController : Controller
{
    private readonly IDistributedOptionsCacheString _fsCache;

    public HomeController(IDistributedOptionsCacheString optionsCache)
    {
        _fsCache = optionsCache;
    }

    //This uses GetAllKeyValues to obtain a dictionary containing all the cache values
    public IActionResult Index()
    {
        var allKeyValues = _fsCache.GetAllKeyValues();
        foreach (var key in allKeyValues.Keys)
        {
            logs.Add($"Key = {key}, Value = {allKeyValues[key]}");
        }

        return View(logs);
    }

    //This displays a page where the user provides a key for the cache entry
    public IActionResult AddCache() 
    {
        return View(); 
    }
 
    //This adds / updates the cache value with the DateTime.Now as a  
    //sortabledate/time string for the cache entry known by the provided key 
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult AddCache(string key) 
    {
        _fsCache.Set(key, DateTime.Now.ToString("s"), null);
        return RedirectToAction("Index");
    }
}

Set with DistributedCacheEntryOptions options parameter

The Set/SetAsync has an optional parameter called options of type DistributedCacheEntryOptions that allows you set up an expiration time for the cache entry. This means the cache entry will be removed once the expiration time is older than the current time defined by DateTime.UtcNow.

The DistributedCacheEntryOptions has three properties, two to form a absolute expiration time and one to set up what is called a sliding expiration. The FileStore cache library supports the two absolute expiration properties, but doesn't support the SlidingExpiration approach to expiration (i.e. it throws a NotImplementedException if the SlidingExpiration isn't null). That's because it would produce a very poor read performance.

Here is an example of adding an expiration time of 5 hours from the point the Set was executed, i.e. five hours later the entry with the cache entry with the key of "test-timeout" will return null.

_fsCache.Set("test-timeout", "my data", 
   new DistributedCacheEntryOptions
      { 
          AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(5)
      });