我在教程https://azure.microsoft.com/en-us/documentation/articles/cache-dotnet-how-to-use-service/之后使用Azure Redis缓存。如何使用此缓存不使用使用webconfig?这是我的代码。
c#代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.ApplicationServer.Caching;
using System.Data;
using System.Data.SqlClient;
namespace MoviesDB.CacheWrappers
{
public class AzureManagedCache
{
DataCache AzureCache = new DataCache("default");
public void Add(string sqlQuery, DataTable records)
{
List<Movie> movies = new List<Movie>();
movies = MovieDBContext.ConvertToMovies(records);
AzureCache.Add("sqlQuery", movies);
}
public void Delete(string sqlQuery)
{
AzureCache.Remove("sqlQuery");
}
public object Read(string sqlQuery)
{
var movie = AzureCache.Get("sqlQuery");
return movie;
}
}
}
和webconfig.xml
<dataCacheClients>
<dataCacheClient name="default">
<!--To use the in-role flavor of Windows Azure Cache, set identifier to be the cache cluster role name
To use the Windows Azure Cache Service, set identifier to be the endpoint of the cache cluster-->
<autoDiscover isEnabled="true" identifier="******.cache.windows.net" />
<localCache isEnabled="true" sync="TimeoutBased" objectCount="100000" ttlValue="300" />
<!--Use this section to specify security settings for connecting to your cache. This section is not required if your cache is hosted on a role that is a part of your cloud service.-->
<securityProperties mode="Message" sslEnabled="true">
<messageSecurity authorizationInfo="******" />
</securityProperties>
</dataCacheClient>
</dataCacheClients>
答案 0 :(得分:0)
以编程方式与托管缓存进行通信的代码:
var cacheSvcUri = "<your-cache-name>.cache.windows.net";
// Setup DataCacheSecurity configuration
string cacheSvcAcsKey = "<your-acs-key>";
var secureAcsKey = new SecureString();
foreach (char c in cacheSvcAcsKey)
{
secureAcsKey.AppendChar(c);
}
secureAcsKey.MakeReadOnly();
// Setup the DataCacheFactory configuration
DataCacheFactoryConfiguration dcfConfig = new DataCacheFactoryConfiguration();
// Set autodiscover for in-role
dcfConfig.AutoDiscoverProperty = new DataCacheAutoDiscoverProperty(true, cacheSvcUri);
DataCacheSecurity factorySecurity = new DataCacheSecurity(secureAcsKey);
dcfConfig.SecurityProperties = factorySecurity;
// Create a configured DataCacheFactory object.
DataCacheFactory dcf= new DataCacheFactory(dcfConfig); // make the DataCacheFactory static as it connects to the cache cluster.
// Get a cache client for the default cache.
DataCache defaultCache = dcf.GetDefaultCache();
defaultCache.Put("One", 1);
defaultCache.Put("Two", 2);
您可以在定义要在缓存租户中与之通信的命名缓存后添加缓存操作。在这里,它是“默认”(DataCache defaultCache = dcf.GetDefaultCache()
)。如果你想与任何其他命名缓存交谈,那么它应该是DataCache defaultCache = dcf.GetCache("<your-named-cache>")