輪詢演算法是最簡單的一種負載均衡演算法。它的原理是把來自使用者的請求輪流分配給內部的服務器:從伺服器1開始,直到伺服器N,然後重新開始迴圈。下面小編為大家整理了c#實現輪詢演算法例項程式碼,希望能幫到大家!
CacheSlidingExpirationHour:時間,快取時間2小時
CountdownCurrentIndexCacheName:快取名稱
log:日誌
m_objCountdownCurrentIndexLock::當前物件
m_snIntervalSecond:定義一個數組,可以視為概率值
說明:0,1,1,1 資料中存了4個數,我們設為總的概率為100%,每個代表25%,所以現在我設定的是當前的概率為75%
存如快取的是資料的索引,取的時候也取的'索引,方法返回索引,轉成int型別
public class CountdownHelper { private const int CacheSlidingExpirationHour = 2; private const string CountdownCurrentIndexCacheName = "OnlineMeetingCountdownCurrentIndex"; private static IAppLog log = ogger(typeof(CountdownHelper)); private static Cache m_cache = e; private static object m_objCountdownCurrentIndexLock = new object(); private static int[] m_snIntervalSecond = new int[] { 0, 1 , 1 , 1}; //1顯示 0不顯示 public CountdownHelper() { } public int GetCountdownAddedSecond() { lock (m_objCountdownCurrentIndexLock) { int nCountdownCurrentIndex = 0; try { object objCountdownCurrentIndex = m_cache[CountdownCurrentIndexCacheName]; if (objCountdownCurrentIndex == null) { //如果需要加快取的,就用下面的 //m_rt(CountdownCurrentIndexCacheName, 1, null, soluteExpiration, Hours(CacheSlidingExpirationHour), emovable, null); //不用加快取的用下面的 m_rt(CountdownCurrentIndexCacheName, 1, null, soluteExpiration, idingExpiration, emovable, null); } else { nCountdownCurrentIndex = (int)objCountdownCurrentIndex; if (nCountdownCurrentIndex == m_th - 1) { m_cache[CountdownCurrentIndexCacheName] = 0; } else { m_cache[CountdownCurrentIndexCacheName] = nCountdownCurrentIndex + 1; } } return m_snIntervalSecond[nCountdownCurrentIndex]; } catch (Exception __error) { //如果需要記錄錯誤日誌的,可以記錄到這裡,我這裡沒有加 //r("功能介紹GetCountdownAddedSecond:" + __age); if (nCountdownCurrentIndex > m_th - 1) { nCountdownCurrentIndex = m_th - 1; } return m_snIntervalSecond[nCountdownCurrentIndex]; } } } }
這個功能的需求是:業務部門需要監控當前頁面的曝光率,所以需要用概率去判斷當前的曝光程式碼如何在頁面上交替顯示,起初是曝光率為50%,所以陣列中直接就是new int[] { 0, 1},後來改成75%,就是上面的程式碼,所以這樣既可以監控曝光,有可以控制曝光程式碼。
前臺呼叫是用AJAX方式:
說明:等於1,將曝光程式碼新增到頁面,否則不加
1
$("/Topic/GetCountdownAddedSecond", function (data) { if (data) { if ( == 1) { var img_html = "<img src="https://d_directed_treatment ="display:none;">"; $("#adver")(img_html); } } }, "json");