在.NET Core依赖注入中,`StackExchange.Redis.ConnectionMultiplexer`应该是`AddSingleton`还是`AddScope`?

ee7vknir  于 5个月前  发布在  Redis
关注(0)|答案(1)|浏览(53)

我正在使用StackExchange.Redis添加一个Redis连接到.NET Core,它目前看起来像这样:

public static IServiceCollection AddRedisMultiplexer(
    this IServiceCollection services,
    Func<ConfigurationOptions> getOptions = null)
{
    // Get the options or assume localhost, as these will be set in Startup.ConfigureServices assume they won't change
    var options = getOptions?.Invoke() ?? ConfigurationOptions.Parse("localhost");

    // The Redis is a singleton, shared as much as possible.
    return services.AddSingleton<IConnectionMultiplexer>(provider => ConnectionMultiplexer.Connect(options));
}

字符串
然后在Startup

public void ConfigureServices(IServiceCollection services)
{
    services.AddRedisMultiplexer(() => 
        ConfigurationOptions.Parse(Configuration["ConnectionStrings:Redis"]));
    ...


这意味着我可以在任何地方使用IConnectionMultiplexer进行依赖注入。
我的问题是:ConnectionMultiplexerdesigned to be reused,所以我使用AddSingleton为整个应用程序保留一个示例。但是我也可以使用AddScoped在请求期间使用一个示例。哪一个更好,为什么?

htzpubme

htzpubme1#

应用程序的预期负载是多少?如果你有很多并发,我认为使用AddScoped将意味着为每个请求启动和关闭连接的大量不必要的负担。
此外,这些观察IMHO表明,您应该使用AddSingleton
(...)您很少会想要简单地使用ConnectionMultiplexer,因为其想法是重用此对象。
Redis的另一个常见用途是作为发布/订阅消息分发工具;这也很简单,并且**在连接失败的情况下,ConnectionMultiplexer将处理重新订阅所请求通道的所有细节。
此外,您将节省保存内存,只有一个ConnectionMultiplexer示例(恕我直言)。

相关问题