2012-05-15 262 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