14

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?

1
  • Marc Gravell emphasized that the IDatabase object is a cheap throw-away object in this in the response to this similar question: stackoverflow.com/questions/25591845/… Commented Dec 6, 2016 at 18:12

1 Answer 1

15

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");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.