NB: HttpApplicationState, HttpSessionState, HttpRuntime.Cache and .Net4 MemoryCache work in-process (memory) in Azure (asp caching). You can even use Session with SqlAzure (but why?).
NB: Windows Azure Shared Caching is different- it's the older paid-for caching.
- You can't use cache with ExtraSmall instances
- Co-located: shares VM with worker/web role (e.g. 30% memory) but is distributed across instances.
Solution Explorer: Role - Properties - Cache tab.
You'll need the storage account credentials forMicrosoft.WindowsAzure.Plugins.Caching.ConfigStoreConnectionString
- Dedicated role: Add New Cache Worker Role
- Add the Nuget package Windows Azure Caching (Microsoft.WindowsAzure.Caching)
- For ASP sites, you can enable Session state and OutputCaching in web.config.
Configuration
You need to change the web/app.config, specifically the role name here (otherwise the error is ErrorCode<UnspecifiedErrorCode>:SubStatus<ES0001>:The role [cache cluster role name] was not found in the current deployment.
)
<dataCacheClients>
<dataCacheClient name="default">
<autoDiscover isEnabled="true" identifier="MyWebRole" />
DataCache
- Either: var dataCache = new DataCache(cacheName) (eg "default")
- Or: via var dataCache = new DataCacheFactory().GetCache(cacheName)
- dataCache.Add(key, value) throws a DataCacheException if it already exists.
Use dataCache.Put(key, value) instead.
Named caches
- Named caches have an expiration policy- one of Absolute, Sliding or None (permanent- time = 0)
- You can override the Time to Live with TimeSpans when dataCache.Add/Put
Example
using System;
using Microsoft.ApplicationServer.Caching;
namespace MartinWeb.Cloud
{
public class CacheCloud
{
private readonly string _cacheName;
public CacheCloud(string cacheName = null)
{
_cacheName = cacheName;
}
private DataCache FindDataCache()
{
if (string.IsNullOrEmpty(_cacheName))
{
return new DataCacheFactory().GetDefaultCache();
}
return new DataCache(_cacheName);
}
public void Add(string key, object value)
{
Add(key, value, TimeSpan.FromMinutes(10));
}
public void Add(string key, object value, TimeSpan timeSpan)
{
var dataCache = FindDataCache();
//for example only- why not just use Put?
try
{
dataCache.Add(key, value, timeSpan);
}
catch (DataCacheException)
{
//already exists, add or replace
dataCache.Put(key, value, timeSpan);
}
}
public T Get<T>(string key) where T : class
{
var dataCache = FindDataCache();
return dataCache.Get(key) as T;
}
public TimeSpan RemainingTimeToLive(string key)
{
var dataCache = FindDataCache();
return dataCache.GetCacheItem(key).Timeout;
}
}
}