【问题标题】:Configure Asp.net MVC project and EntityFramework to use Redis as Cache provider配置 Asp.net MVC 项目和 EntityFramework 以使用 Redis 作为缓存提供程序
【发布时间】:2018-10-13 21:37:38
【问题描述】:

我想使用EF Second Level Cache,并将ASP.NET MVC 项目中EF 的默认缓存提供程序更改为使用Redis 而不是其InMemory 缓存提供程序。

我有以下 MVC Core 示例代码:

// Add Redis cache service provider
var jss = new JsonSerializerSettings
{
    NullValueHandling = NullValueHandling.Ignore,
    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};

const string redisConfigurationKey = "redis";
services.AddSingleton(typeof(ICacheManagerConfiguration),
    new CacheManager.Core.ConfigurationBuilder()
        .WithJsonSerializer(serializationSettings: jss, deserializationSettings: jss)
        .WithUpdateMode(CacheUpdateMode.Up)
        .WithRedisConfiguration(redisConfigurationKey, config =>
        {
            config.WithAllowAdmin()
                .WithDatabase(0)
                .WithEndpoint("localhost", 6379);
        })
        .WithMaxRetries(100)
        .WithRetryTimeout(50)
        .WithRedisCacheHandle(redisConfigurationKey)
        .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromMinutes(10))
        .Build());
services.AddSingleton(typeof(ICacheManager<>), typeof(BaseCacheManager<>));

我的项目不是MVC Core,它是MVC。我也使用StructureMaps 作为 国际奥委会。

现在我有 2 个问题:

  1. 我应该如何在我的项目中配置EF 以使用Redis 作为它的二级缓存 Provider(我正在使用this 包)?
  2. 我可以在我的计算机上的单独项目中以这种方式使用缓存中保存的数据 (Redis)(在多个应用程序之间共享 MVC 应用程序的缓存)吗?

【问题讨论】:

    标签: c# asp.net-mvc entity-framework redis structuremap


    【解决方案1】:

    StructureMap 中的 Redis

    在 StructureMap 中有相当多的代码来注册该服务。单例在该系统中略有不同,您最好使用“工厂”模式来创建和管理您的 redis 缓存。 SM 有一个auto-factory 可以解决问题。

    如果您愿意,我可以在这里发布一些基本代码。但是 - 你需要在你的环境中进行测试才能让它工作(我不喜欢在堆栈上发布理论代码)。

    如果你以前没有使用过 redis,我会创建一个控制台应用程序,并确保你可以配置它并让它在将 IOC 和你的 .Net MVC 应用程序插入图片之前运行(你是一个强大的编码器,所以我不会告诉你一些你还不知道的东西)。

    您的其他应用可以使用 Redis 缓存吗?

    是的。只要他们有权访问您创建的端点(在上面的代码中,它正在侦听localhost:6379)。

    您可以使用在 MVC 应用程序中使用的相同“配置”设置。当你这样做时,两个应用程序将访问同一个 redis“服务器”并共享相同的缓存对象。

    以您对数据库的相同方式看待 redis:只要两个系统使用相同的“配置”(例如 - 连接字符串),那么它们就可以访问相同的数据。

    redis 超级快而且非常酷。你会喜欢的!

    完全未经测试的示例代码

    这里有一个快速概述,以便我对代码结构的评论更有意义。如果其他人有调整建议,请随时添加到 cmets,我会更新。

    public interface ICacheManagerConfigFactory {
        ICacheManagerConfiguration CreateCacheManager();
    }
    
    public CacheManagerFactory:ICacheManagerConfigFactory {
    
        private static ICacheManagerConfiguration _cache;
        private static object syncRoot = new Object();
        
        public ICacheManagerConfiguration CreateCacheManager() {
    
            if(_cache!=null) { return _cache; } 
            //locking to make sure that we only create 1 _cache object (thread-safe)
            lock(syncRoot) {
                //idiot-proofing our thread-safe code
                if(_cache!=null) { return _cache; } 
                //create _cache if it doesn't already exist
                var jss = new JsonSerializerSettings {
                    NullValueHandling = NullValueHandling.Ignore,
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                };  
                _cache= new CacheManager.Core.ConfigurationBuilder()
                   .WithJsonSerializer(serializationSettings: jss, deserializationSettings: jss)
                   ... etc ...
                   .Build();
            }
            return _cache;
        }
    }
    

    而且,这只是一种快速测试方法,它证明我们可以从内存中提取静态配置。它也来自 SM 的 auto-factory 文档。

    public void Simple_factory_creation() {
        var container = new Container(cfg => {
            cfg.For<ICacheManagerConfiguration>().Use<CacheManagerFactory>();
            cfg.For<ICacheManagerConfigFactory>().CreateFactory();
        });
    
        var cache = container.GetInstance<ICacheManagerConfiguration>();
    
    }   
    

    【讨论】:

    • 谢谢你,我忘了在我的问题中提到 EF(我更新了它),但我想更改 EF 缓存提供程序以使用 Redis。真的我想使用 Redis 的 EF 二级缓存。我为ICacheManagerConfiguration 配置了StructureMap 而没有Factory 方法(直接在IOC 配置中),但EF 缓存尚未存储在Redis 中。似乎还不够。也许我应该为DbConfiguration 实现一个自定义类来强制EF CachingProvider 使用Redis
    猜你喜欢
    • 2017-09-28
    • 2015-11-28
    • 2019-08-03
    • 2014-12-24
    • 1970-01-01
    • 1970-01-01
    • 2011-03-06
    • 2016-04-19
    • 2010-10-26
    相关资源
    最近更新 更多