9
votes

I'm designing a web service which uses Redis as a database, and I want to know the best practices for using Redis connecting with StackService client.

The point is that I've been reading about Redis and I found that the best way to interact with the server is by using a single concurrent connection.

The problem is that despite I'm using PooledRedisClientManager each time that a web client makes a request to the web service I get a one more connected client (opened connection) to the redis server and this number of connected client increases without limit consuming more and more memory.

The sample 'fault' code:

PooledRedisClientManager pooledClientManager = new PooledRedisClientManager("localhost");
var redisClient = pooledClientManager.GetClient();
using (redisClient)
{
   redisClient.Set("key1", "value1");
}

What I did to solve the problem, is create a class implementing the singleton pattern with a static RedisClient var; Which if the redisClient is not initialized creates a new one, and if it is, returns the initialized one.

Solution:

public class CustomRedisPooledClient
{
    private static CustomRedisPooledClient _instance = null;
    public RedisClient redisClient = null;

    // Objeto sincronización para hacer el Lock 
    private static object syncLock = new object();

    private CustomRedisPooledClient()
    {
        redisClient = new RedisClient("localhost");
    }

    public static CustomRedisPooledClient GetPooledClient()
    {
        if (_instance == null)
        {
            lock (syncLock)
            {
                if (_instance == null)
                {
                    _instance = new CustomRedisPooledClient();
                }
            }
        }
        return _instance;
    }
}

CustomRedisPooledClient customRedisPooledClient = CustomRedisPooledClient.GetPooledClient();
using (customRedisPooledClient.redisClient)
{
    customRedisPooledClient.redisClient.Set("key1", "value1");
}

Is this a good practice?

Thank you in advance!

1
Why did you pull a redisClient from the pool but are not using it? but are using pooledClientManager instead? - mythz
It was a mistake writing the question, now it's corrected - Roberto Zamora
k, tho I would edit your question because your 'fault code' now works and the Solution provided is not ideal. Add what the problem was and refer to the accepted answer for the ideal solution. - mythz

1 Answers

16
votes

I used PooledRedisClientManager and it works fine:

Sample code that I run only once:

static PooledRedisClientManager pooledClientManager = new PooledRedisClientManager("localhost");

and code I run on many threads:

var redisClient = pooledClientManager.GetClient();
using (redisClient)
{
    redisClient.Set("key" + i.ToString(), "value1");
}

and I have only 11 clients connected to the server.