在最近項目開發過程中,在進行任務調度處理過程中,出現了一個問題,它的線程數暴長,從20多個可以到1000多個,如果你的服務器性能好的話,可以到10000多個,太恐怖了,就算你的服務再好,早晚有一天也會被new Redis炸干!哈哈!
解決方法:
使用單例模式減少new redis的次數
對於我們應用程序的線程,如果它持續增長,那麼,你就要看一下那麼非托管資源是否被釋放了,這個要重視起來。
有人說這個文章是個標題黨,不知道從哪裡發明的這個“新名詞”,所以我把代碼也發一下吧
/// <summary>
/// Redis客戶端
/// </summary>
public class RedisClient : IDisposable
{
public static RedisClient Instance;
private ConnectionMultiplexer conn;
private IDatabase cache;
Private static Object lockObj=new Object();
#region Constructors
static RedisClient()
{
lock(lockObj)
{
Instance = new RedisClient();
}
}
private RedisClient()
{
conn = ConnectionMultiplexer.Connect("localhost"); //var conn = ConnectionMultiplexer.Connect("redis0:6380,redis1:6380,allowAdmin=true");
cache = conn.GetDatabase();
}
#endregion
#region Behaviors
public void Push(string key, object value)
{
cache.Push(key, value);
}
public object Pop(string key)
{
return cache.Pop(key);
}
public T Pop<T>(string key)
{
return cache.Pop<T>(key);
}
public T Get<T>(string key)
{
return cache.Get<T>(key);
}
public object Get(string key)
{
return cache.Get(key);
}
public void Set(string key, object value)
{
cache.Set(key, value);
}
#endregion
#region IDisposable
public void Dispose()
{
conn.Dispose();
}
#endregion
}