在.NET核心依赖项注入中,`StackExchange.Redis.ConnectionMultiplexer`应该是`AddSingleton`还是`AddScope`?
我正在使用StackExchange.Redis向.NET Core添加一个Redis连接,它当前看起来像这样:在.NET核心依赖项注入中,`StackExchange.Redis.ConnectionMultiplexer`应该是`AddSingleton`还是`AddScope`?,redis,.net-core,stackexchange.redis,Redis,.net Core,Stackexchange.redis,我正在使用StackExchange.Redis向.NET Core添加一个Redis连接,它当前看起来像这样: public static IServiceCollection AddRedisMultiplexer( this IServiceCollection services, Func<ConfigurationOptions> getOptions = null) { // Get the options or assume localhost,
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));
}
这意味着我可以在任何地方使用IConnectionMultiplexer
进行依赖注入
我的问题是:
ConnectionMultiplexer
is,因此我使用AddSingleton
为整个应用程序保留一个实例。但是,我也可以使用AddScoped
在请求期间使用一个。哪一个更好,为什么 应用程序的预期负载是多少?如果您有很多并发性,我认为使用AddScoped
将意味着为每个请求启动和关闭连接会带来很多不必要的负担
这些观察结果还表明,您应该使用AddSingleton
(…)您想使用
ConnectionMultiplexer简单介绍一下,因为其思想是重用这个对象
redis的另一个常见用途是作为发布/订阅消息分发工具;
这也很简单,在连接失败的情况下
ConnectionMultiplexer将处理重新订阅的所有详细信息
请求的频道。
另外,只有一个
ConnectionMultiplexer
(IMHO)实例可以节省内存。该应用程序需要扩展,但我不希望出现大量并发请求。我的意见是也使用AddSingleton
,但我对使用StackExchange.Redis
相当陌生,有点不确定复用器的重用程度。@Keith复用器似乎甚至可以通过传递连接URL来处理多个Redis实例(主/从),所以我认为这是一个不错的选择。
public void ConfigureServices(IServiceCollection services)
{
services.AddRedisMultiplexer(() =>
ConfigurationOptions.Parse(Configuration["ConnectionStrings:Redis"]));
...