17

The idea is to use less connection and better performance. Does the connection expire at any time?

And for another question, does _redis.GetDatabase() open new connection?

private static ConnectionMultiplexer _redis;
private static IDatabase _db;

public RedisCacheProvider(string configuration)
{
    if (_redis == null)
        lock (myLock)
            if (_redis == null)
            {
                _redis = ConnectionMultiplexer.Connect(configuration);
                _db = _redis.GetDatabase();
            }
}

public async Task<string> GetString(string key)
{
    string result = null;

    RedisValue val = await _db.StringGetAsync(key);

    if (val.HasValue)
        result = val;

    return result;
}

1 Answer 1

25

No, a multiplexer doesn't expire. No GetDatabase doesn't open a new connection. This is all covered in basics.md - in particular:

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

Sign up to request clarification or add additional context in comments.

7 Comments

Is there a performance impact by using a static IDatabase object vs calling GetDatabase every time you need to call one of it's methods?
@Aaron for db 0-15 and without an async state, in recent builds: not at all. (note: .GetDatabase() is db 0 without an async-state, so: no overhead). For older builds, dbs above 15, or with an async-state: minimal - a single object is allocated
@tehmas I mean that it is simply a token class that carries the multiplexer, chosen database number, and (rarely) state object; for "low" database numbers (for my arbitrary definition of low), there's a good chance it'll also be memoized at the multiplexer level, i.e. if you call GetDatabase(2) 3 times, you'll probably get the same object 3 times, not 3 different objects; but either way: it doesn't need to do anything - calling GetDatabase doesn't talk to the server, etc
@tehmas I'd need to see code; short version is: you can't, so I expect the problem is in your test rig; here's the code - as you can see, other than validating the args, it doesn't do anything except either return a pre-existing instance, or a new simple object
@tehmas and in case you're wondering "does the constructor talk to the multiplexer" - no: github.com/StackExchange/StackExchange.Redis/blob/master/src/… and github.com/StackExchange/StackExchange.Redis/blob/master/src/…
|

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.