Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should StackExchange.Redis IDatabase object be used in a multi-threaded application?

I'm getting mixed messages from the StackExchange.Redis documentation about how to use an IDatabase. In the Basic Usage doc it says:

The object returned from GetDatabase is a cheap pass-thru object, and does not need to be stored.

This give the impression that I should call GetDatabase for every Redis operation.

However, from the Pipelining and Multiplexing doc, by the language and example code, it seems that you should re-use the IDatabase object to take advantage of pipelining and multiplexing. I say it seems that way because the example code block re-use the same db, and because it talks about re-using the connection. Now, I'm not sure if connection refers to the object returned by GetDatabase, or the underlying connection, or what.

I'm accessing Redis from an asp.net web application so I need to optimize my code for highly multi-threaded access. Should I call GetDatabase with every operation, or should IDatabase objects be shared by multiple threads? If that latter, to what extent? Should one database object be shared across the entire application indefinitely?

like image 961
Sean Avatar asked Oct 05 '16 22:10

Sean


1 Answers

Use the ConnectionMultiplexer across multiple threads. I'm using .NET Core dependency injection but you could just use

static readonly Lazy<ConnectionMultiplexer> SharedMultiplexer => 
    new Lazy<ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect("localhost"));

Call GetDatabase() just before you need it in the specific request.

Use inline async and await continuation methods in an asynchronous action to ensure that you optimise for highly concurrent access...

string value = await SharedMultiplexer.GetDatabase().StringGetAsync("mykey");
like image 125
Keith Avatar answered Oct 29 '22 18:10

Keith