The correct way of using StackExchange.Redis

2020-08-15 07:24发布

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条回答
做自己的国王
2楼-- · 2020-08-15 07:57

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.

查看更多
登录 后发表回答