我正在使用 StackExchange.Redis 将Redis连接添加到.NET Core,当前看起来像这样:
I'm adding a Redis connection to .NET Core using StackExchange.Redis, it currently looks something like this:
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)); }然后在启动
public void ConfigureServices(IServiceCollection services) { services.AddRedisMultiplexer(() => ConfigurationOptions.Parse(Configuration["ConnectionStrings:Redis"])); ...这意味着我可以在任何地方使用 IConnectionMultiplexer 进行依赖项注入.
This then means I can use IConnectionMultiplexer for the dependency injection anywhere.
我的问题是: ConnectionMultiplexer 是被设计为可重用,因此我使用了 AddSingleton 为整个应用程序保留一个实例.但是,我也可以使用 AddScoped 在请求期间使用一个.哪个更好?为什么?
My question is: ConnectionMultiplexer is designed to be reused, so I've used AddSingleton to keep a single instance for the entire application. However I could also use AddScoped to use one for the duration of the request. Which is better and why?
推荐答案该应用程序的预期负载是多少?如果您有很多并发性,我认为使用 AddScoped 意味着为每个请求启动和关闭连接的大量不必要的负担.
What is the load expected to the app ? If you have much concurrency, I think using AddScoped would mean a lot of unnecessary burden to initiate and close connections for every request.
恕我直言,这些观察结果还表明您应该使用 AddSingleton
Also these observations IMHO show that you should use AddSingleton
(...)极少见的是您想使用简要介绍ConnectionMultiplexer,因为其想法是重复使用该对象.
(...) it is exceptionally rare that you would want to use a ConnectionMultiplexer briefly, as the idea is to re-use this object.
redis的另一种常见用法是作为发布/订阅消息分发工具;这也很简单,如果连接失败,ConnectionMultiplexer将处理重新订阅的所有详细信息请求的频道.
Another common use of redis is as a pub/sub message distribution tool; this is also simple, and in the event of connection failure, the ConnectionMultiplexer will handle all the details of re-subscribing to the requested channels.
此外,您将保存只有一个 ConnectionMultiplexer (IMHO)实例的内存.
Also, you will save memory having only one instance of ConnectionMultiplexer (IMHO).
更多推荐
在.NET Core依赖项注入中,StackExchange.Redis.ConnectionMultiplexer应该是AddSingleton还是AddSc
发布评论