Sql Server 讀寫分離
阿新 • • 發佈:2021-08-10
連結:https://blog.csdn.net/qq_36445227/article/details/108889448
負載均衡程式碼:
public class ConnString { private static List<string> ReadConnStringList = new List<string>() { "ReadDB1", "ReadDB2", "ReadDB3" };//模擬連線字串 private static string WriteConnString = "WriteDB"; private static int index = 0; private static List<int> Scoure = new List<int>() { 1, 2, 6 }; private static List<string> ReadScourList = new List<string>() { }; static ConnString() { int tempindex = 0; foreach (int item in Scoure) { for (int i = 0; i < item; i++) { ReadScourList.Add(ReadConnStringList[tempindex]); } tempindex++; } } public static string GetConnStringMethod(CnnEnum cnn ) { string str = string.Empty; switch (cnn) { case CnnEnum.Read: str = GetReadStr(); break; case CnnEnum.Write: str=WriteConnString; break; default: break; } return str; } /// <summary> /// 輪詢策略 /// </summary> /// <returns></returns> public static string GetReadStr() { // return ReadConnStringList[index++% ReadConnStringList.Count];//輪詢規則 return ReadScourList[new Random(index++).Next(0, ReadScourList.Count)];//權重規則 } public enum CnnEnum { Read, Write } }
測試程式碼
//for (int i = 0; i < 10; i++) //{ // Console.WriteLine(ConnString.GetConnStringMethod(ConnString.CnnEnum.Read)); //}
萌橙 你瞅啥?