我正在設計一個使用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