Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The correct way of using StackExchange.Redis

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;
}
like image 863
Babak Avatar asked Aug 31 '14 12:08

Babak


People also ask

How does Redis work with StackExchange?

There are 3 primary usage mechanisms with StackExchange.Redis: Synchronous - where the operation completes before the methods returns to the caller (note that while this may block the caller, it absolutely does not block other threads: the key idea in StackExchange.Redis is that it aggressively shares the connection between concurrent callers)

What can I do with Redis?

The entire range of redis database commands covering all redis data types is available for use. Another common use of redis is as a pub/sub message distribution tool; this is also simple, and in the event of connection failure, the ConnectionMultiplexer will handle all the details of re-subscribing to the requested channels.

Where to get started with Redis binaries?

StackExchange.Redis Tutorial - Getting started with... Binaries for StackExchange.Redis are available on Nuget, and the source is available on Github.

How is data stored in stackexchangeredis?

Looking at the code of StackExchangeRedis, we can see that it uses the HMSET command to save data into Redis. From this, we can guess that our data is stored as hash.


1 Answers

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.

like image 184
Marc Gravell Avatar answered Nov 12 '22 09:11

Marc Gravell