在最近項目開發過程中,在進行任務排程處理過程中,出現了一個問題,它的線程數暴長,從20多個可以到1000多個,如果你的伺服器性能好的話,可以到10000多個,太恐怖了,就算你的服務再好,早晚有一天也會被new Redis炸幹!哈哈!
原因:非托管資源使用過多,沒有得到釋放
一 連接配接網絡資源過多,如redis,mongo,sql等
二 原生的資料庫對象建立過多(自己沒有連接配接池,現在的linq沒這問題)
三 檔案資源使用過多,沒有得到釋放
解決方法:
使用單例模式減少new操作的次數
對于我們應用程式的線程,如果它持續增長,那麼,你就要看一下那麼非托管資源是否被釋放了,這個要重視起來。
有人說這個文章是個标題黨,不知道從哪裡發明的這個“新名詞”,是以我把代碼也發一下吧
/// <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
}