【问题标题】:Does the EF+ option work with redis, and does it work if redis fails?EF+ 选项是否适用于 redis,如果 redis 失败,它是否有效?
【发布时间】:2022-08-08 19:18:19
【问题描述】:

Entity Framework plus 是否支持 Azure Redis 缓存

我必须为特定的 EF 实体使用 Azure Redis 缓存实现 EF+ 查询缓存,以缓存特定时间的结果

参考:-https://entityframework-plus.net/query-cache

标签: c# asp.net-mvc entity-framework azure-redis-cache entity-framework-plus


【解决方案1】:

Entity Framework plus 是否支持 Azure Redis 缓存

是的,它支持这里是创建redis缓存和实体框架的步骤

首先,在 Azure 门户中创建 Redis 缓存环境并复制主机名和访问密钥

现在在 Visual Studio 中创建一个项目,并将访问密钥和主机名替换为 azure 门户中的缓存详细信息。

然后从 Nuget 包中添加实体框架包。

创建新类并添加以下代码

public static class AzureCache  
    {  
        private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>  
        {  
            string cacheConnection = ConfigurationManager.AppSettings["CacheConnection"].ToString();  
            return ConnectionMultiplexer.Connect(cacheConnection);  
        });  
  
        public static ConnectionMultiplexer Connection  
        {  
            get  
            {  
                return lazyConnection.Value;  
            }  
        }  
  
  
        public static T Get<T>(string cacheKey)  
        {  
            return Deserialize<T>(Connection.GetDatabase().StringGet(cacheKey));  
        }  
  
        public static object Get(string cacheKey)  
        {  
            return Deserialize<object>(Connection.GetDatabase().StringGet(cacheKey));  
        }  
  
        public static void Set(string cacheKey, object cacheValue)  
        {  
            Connection.GetDatabase().StringSet(cacheKey, Serialize(cacheValue));  
        }  
  
        private static byte[] Serialize(object obj)  
        {  
            if (obj == null)  
            {  
                return null;  
            }  
            BinaryFormatter objBinaryFormatter = new BinaryFormatter();  
            using (MemoryStream objMemoryStream = new MemoryStream())  
            {  
                objBinaryFormatter.Serialize(objMemoryStream, obj);  
                byte[] objDataAsByte = objMemoryStream.ToArray();  
                return objDataAsByte;  
            }  
        }  
  
        private static T Deserialize<T>(byte[] bytes)  
        {  
            BinaryFormatter objBinaryFormatter = new BinaryFormatter();  
            if (bytes == null)  
                return default(T);  
  
            using (MemoryStream objMemoryStream = new MemoryStream(bytes))  
            {  
                T result = (T)objBinaryFormatter.Deserialize(objMemoryStream);  
                return result;  
            }  
        }  
    }  

一切完成后,我测试您的应用程序,它应该以下列方式显示

有关完整信息,您可以通过此document

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-17
    • 2014-10-02
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    • 2013-02-25
    相关资源
    最近更新 更多