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!