StackExchange / StackExchange.Redis

General purpose redis client
https://stackexchange.github.io/StackExchange.Redis/
Other
5.87k stars 1.51k forks source link

Guidance for using ConnectionMultiplexer with dependency injection and health checks #2537

Closed adamsitnik closed 1 year ago

adamsitnik commented 1 year ago

I would like to do the following:

Based on the available docs I've assumed that I should register a singleton so the instance can be reused (perf):

builder.Services.AddSingleton<IConnectionMultiplexer>(sp => ConnectionMultiplexer.Connect(settings.ConfigurationOptions));

Then I read the implementation of popular health check for ConnectionMultiplexer, which disposes the ConnectionMultiplexer on exception.

What happens when I successfully connect via ConnectionMultiplexer.Connect, but later the connection fails? Is ConnectionMultiplexer able to reconnect on it's own and I should keep using a singleton? I saw the ConnectionFailed and ConnectionRestored events, so I would assume that to be true?

cc @mgravell @NickCraver @damianedwards @eerhardt

NickCraver commented 1 year ago

Correct: safe to use a singleton that doesn't change - we reconnect internally, and you can observe via events what's going on (as well as ILogger bits next release).

Only if your configuration is changing to different endpoints (e.g. moving clusters, part of some migration for example) would you want to swap that singleton out. Most other things like passwords and such are observed live, so we'll respect the options passed in and get live values from it (to support things like MI).

adamsitnik commented 1 year ago

@NickCraver thank you very much!

eerhardt commented 1 year ago

What about https://learn.microsoft.com/en-us/azure/azure-cache-for-redis/cache-best-practices-connection#using-forcereconnect-with-stackexchangeredis? And this functionality in ASP.NET?

NickCraver commented 1 year ago

@eerhardt I wouldn't advise using the force reconnect pattern at all - it was a pattern from before we knew about a lot of the various problems hitting many cloud teams (which we rapidly improved once seeing them - joining MS), these days it only causes more drops and problems. The multiplexer handling this internally results in fewer errors (e.g. things not dropped on the floor, but buffered and tried when connected internally, etc.).

eerhardt commented 12 months ago

Thanks @NickCraver!