-->

Best practice when using Azure AppFabric Caching S

2020-07-18 08:49发布

问题:

I have successfully started using Azure AppFabric Caching Service, but I' not sure what the best practice way of creating the DataCacheFactory object is. Now I'm creating it for every call into the cache, but apparently this is not the ideal way of doing it...

Some advise call for a Singleton. But I'm not sure I understand how this would be implemented (not the actual Singleton class, but how to tie it all together).

Today I have a CacheProvider class that is created for me using Ninject where I can do Get/Put/Remove operations. For each of these methods I create the DataCacheFactory object and then call .GetDefaultCache() to get the DataCache object, where I call Put/Get/Remove respectively. I do this in a single method that looks like this:

private T Cache<T>(Func<DataCache, T> cacheAction)
{
    using (DataCacheFactory dataCacheFactory = new DataCacheFactory())
    {
        DataCache dataCache = dataCacheFactory.GetDefaultCache();
        return cacheAction(dataCache);
    }
}

I'm now pretty sure that this is not-so-clever-idea, I should instead be getting the DataCache object via a Singleton where the DataCacheFactory object is just created once. BUT how will that object survive between requests? And how does that work with > 1 instance on Azure?

Hope all this makes sense and that somebody with more experience than me (3 hours) can help me out.

回答1:

Singleton objects live at the application scope. Simply declare your private DataCache object on a global static level, provide a property Get that instantiates the object if it is null or returns the object if it is not null.

This way, you will be paying the cost of instrumenting configuration and connection of the cache only once per application recycle.

Each instance will instantiate its own DataCache object and it is ok.

The actual data, where the cache is stored is not stored on your local machine's memory, but in Azure's dedicated cache servers that are distributed and mega-fast.