New connection is made each time a new StackExchangeRedisCacheClient() is set
I tried to use this package in an ASP.NET MVC 5 application.
I added the following code to a global/base controller
[Authorize]
public class BaseController : Controller
{
protected ILog Log { get; private set; }
protected ICacheClient Cache { get; private set; }
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
var serializer = new NewtonsoftSerializer();
Cache = new StackExchangeRedisCacheClient(serializer);
}
}
After rolling my code to production, the CPU on the web server spiked to an unmanageable level. When I reviewed my Redis server's logs, I can see that a new connection to the Redis server is made for each Http Request that reach the controller.
Apparently, each time StackExchangeRedisCacheClient() is called, a connection to the database is opened. Is this by design or is this an issue? I was hoping that I can create a instance but a connection to be opened only when the object is actually used.
Should I only create a instance of StackExchangeRedisCacheClient() only when I need to use it? Also, Will the connection to the server closes automatically or do I need to manually call Cache.Dispose() for that to happen?
Have you tried making the Cache property static and only creating it once? If not I would try that first. Creating a new StackExchangeRedisCacheClient on every request can be costly because in turn each instance creates a new ConnectionMultiplexer which is costly.
Also I cannot tell from the code you posted but an easy win for performance would be to use async controller methods which in-turn use the appropriate async methods on ICacheClient. Just a thought.
Did this work for you @malhayek2014?
Yes. it did. thank you