我正在设计一个使用Redis作为数据库的Web服务,并且我想知道使用Redis连接到StackService客户端的最佳实践。Redis服务堆栈连接客户端
问题是,我一直在阅读关于Redis的内容,并且发现与服务器交互的最佳方式是使用单个并发连接。
的问题是,尽管我使用PooledRedisClientManager每个网络客户端向web服务我得到Redis的服务器多了一个连接的客户端(已打开的连接)的请求,并且这个数字连接的客户端的时间无限制地增加消耗越来越多的内存。
样品“故障”代码:
PooledRedisClientManager pooledClientManager = new PooledRedisClientManager("localhost");
var redisClient = pooledClientManager.GetClient();
using (redisClient)
{
redisClient.Set("key1", "value1");
}
我做了什么来解决这个问题,是创建一个类实现了静态无功RedisClient
Singleton模式;如果redisClient
未被初始化,那么会创建一个新的,如果是,则返回初始化的那个。
解决方案:
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");
}
这是一个好的做法呢?
预先感谢您!
为什么你从池中取出一个** redisClient **,但没有使用它?但是正在使用** pooledClientManager **呢? – mythz
写这个问题是一个错误,现在它已被纠正 –
k,我会编辑你的问题,因为你的'错误代码'现在可以工作,**解决方案**提供的并不理想。添加问题所在,并参考理想解决方案的接受答案。 – mythz