2012-05-15 265 views
9

我正在设计一个使用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"); 
} 

这是一个好的做法呢?

预先感谢您!

+0

为什么你从池中取出一个** redisClient **,但没有使用它?但是正在使用** pooledClientManager **呢? – mythz

+0

写这个问题是一个错误,现在它已被纠正 –

+1

k,我会编辑你的问题,因为你的'错误代码'现在可以工作,**解决方案**提供的并不理想。添加问题所在,并参考理想解决方案的接受答案。 – mythz

回答

16

我用PooledRedisClientManager和正常工作:

示例代码,我只运行一次

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

和代码,我在许多线程上运行:

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

和我只有11个客户端连接到服务器。

+0

如果我这样做,我会在浏览器发出的每个请求中获得一个新线程。我已经调试过它,并且在线redisClient.Set(“key”+ i.ToString(),“value1”)时创建了一个新线程(客户端)。被执行,我放松控制,似乎将永远打开。我做了一个测试刷新调用服务URL的网页,我已经达到了100个连接的客户端 –

+0

也许问题是我在每个请求上运行代码,是吗? –

+0

您确定没有运行“PooledRedisClientManager pooledClientManager = new PooledRedisClientManager(”localhost“);”每次? – eyossi