Kei*_*ith 6 redis stackexchange.redis .net-core
我正在使用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));
}
Run Code Online (Sandbox Code Playgroud)
然后进去 Startup
public void ConfigureServices(IServiceCollection services)
{
services.AddRedisMultiplexer(() =>
ConfigurationOptions.Parse(Configuration["ConnectionStrings:Redis"]));
...
Run Code Online (Sandbox Code Playgroud)
这意味着我可以IConnectionMultiplexer在任何地方使用依赖注入.
我的问题是:ConnectionMultiplexer是可以重复使用,所以我用AddSingleton,以保持一个实例整个应用程序.但是我也可以AddScoped在请求期间使用一个.哪个更好?为什么?
应用程序的预期负载是多少?如果你有很多并发性,我认为使用AddScoped将意味着为每个请求启动和关闭连接会带来很多不必要的负担.
另外这些观察恕我直言,表明你应该使用 AddSingleton
(...)你想要简单地使用ConnectionMultiplexer是非常罕见的,因为我们的想法是重用这个对象.
redis的另一个常见用途是作为发布/订阅消息分发工具; 这也很简单,如果连接失败,ConnectionMultiplexer将处理重新订阅所请求频道的所有细节.
此外,您将节省只有一个ConnectionMultiplexer(IMHO)实例的内存.
| 归档时间: |
|
| 查看次数: |
1504 次 |
| 最近记录: |