StackExchange.Redis.Extensions icon indicating copy to clipboard operation
StackExchange.Redis.Extensions copied to clipboard

New connection is made each time a new StackExchangeRedisCacheClient() is set

Open malhayek2014 opened this issue 9 years ago • 4 comments

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?

malhayek2014 avatar Aug 15 '17 16:08 malhayek2014

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.

rushfrisby avatar Aug 15 '17 16:08 rushfrisby

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.

rushfrisby avatar Aug 15 '17 16:08 rushfrisby

Did this work for you @malhayek2014?

rushfrisby avatar Aug 27 '17 00:08 rushfrisby

Yes. it did. thank you

malhayek2014 avatar Aug 27 '17 16:08 malhayek2014