我正在创建一个 POC,看看我们是否可以在下一个项目中使用 azure redis 缓存。我查看了这个MSDN文档http://azure.microsoft.com/en-us/documentation/articles/cache-dotnet-how-to-use-azure-redis-cache/#connect-to-cache .
并有以下问题/疑问:
- 连接到 Redis 的唯一方法(优雅)是通过下面的代码?难道不能像你配置的 Redis 缓存一样工作吗?
ConnectionMultiplexer connection = ConnectionMultiplexer.Connect("contoso5.redis.cache.windows.net,ssl=true,password=...");
我们需要在每次获取和设置时调用上面的方法并连接到 Redis?如果不是,我们如何只调用一次并重复使用?
我只能看到 StringGet 和 StringSet。是否也可以设置复杂的 .NET 类型?例子会很好。以下是我过去使用专用 azure 缓存或 ent.Lib 缓存所做的事情。
public class CacheManager {
public void AddToCache(string Id, T value) { string Key = this.MakeKey(Id); if (this.m_Cache.Contains(Key)) { this.m_Cache.Remove(Key); } ------ this.m_Cache.Add(Key, value,CacheItemPriority.Normal, null, expireTime); } }
最佳答案
您可以拥有 ConnectionMultiplexer 的单个实例并将其用于整个应用程序。您不需要为每个 Get/Set 调用创建一个。 你可以找到一个例子http://azure.microsoft.com/blog/2014/06/05/mvc-movie-app-with-azure-redis-cache-in-15-minutes/ 。我正在复制下面的相关代码
private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
{
var config = new ConfigurationOptions();
config.EndPoints.Add(cachename);
config.Password = password;
config.Ssl = true;
config.SyncTimeout = 150;
return ConnectionMultiplexer.Connect(config);
});
您也可以将对象存储在缓存中。我上面提到的同一链接显示了如何将 .NET 对象序列化到缓存中。
关于c# - Azure Redis 缓存获取和设置复杂类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29119722/