- 相關(guān)推薦
c#實(shí)現(xiàn)輪詢算法實(shí)例代碼
輪詢算法是最簡(jiǎn)單的一種負(fù)載均衡算法。它的原理是把來(lái)自用戶的請(qǐng)求輪流分配給內(nèi)部的服務(wù)器:從服務(wù)器1開(kāi)始,直到服務(wù)器N,然后重新開(kāi)始循環(huán)。下面小編為大家整理了c#實(shí)現(xiàn)輪詢算法實(shí)例代碼,希望能幫到大家!
CacheSlidingExpirationHour:時(shí)間,緩存時(shí)間2小時(shí)
CountdownCurrentIndexCacheName:緩存名稱(chēng)
log:日志
m_objCountdownCurrentIndexLock::當(dāng)前對(duì)象
m_snIntervalSecond:定義一個(gè)數(shù)組,可以視為概率值
說(shuō)明:0,1,1,1 數(shù)據(jù)中存了4個(gè)數(shù),我們?cè)O(shè)為總的概率為100%,每個(gè)代表25%,所以現(xiàn)在我設(shè)置的是當(dāng)前的概率為75%
存如緩存的是數(shù)據(jù)的索引,取的時(shí)候也取的索引,方法返回索引,轉(zhuǎn)成int類(lèi)型
public class CountdownHelper { private const int CacheSlidingExpirationHour = 2; private const string CountdownCurrentIndexCacheName = "OnlineMeetingCountdownCurrentIndex"; private static IAppLog log = AppLoggerManager.GetLogger(typeof(CountdownHelper)); private static Cache m_cache = HttpContext.Current.Cache; 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_cache.Insert(CountdownCurrentIndexCacheName, 1, null, Cache.NoAbsoluteExpiration, TimeSpan.FromHours(CacheSlidingExpirationHour), CacheItemPriority.NotRemovable, null); //不用加緩存的用下面的 m_cache.Insert(CountdownCurrentIndexCacheName, 1, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null); } else { nCountdownCurrentIndex = (int)objCountdownCurrentIndex; if (nCountdownCurrentIndex == m_snIntervalSecond.Length - 1) { m_cache[CountdownCurrentIndexCacheName] = 0; } else { m_cache[CountdownCurrentIndexCacheName] = nCountdownCurrentIndex + 1; } } return m_snIntervalSecond[nCountdownCurrentIndex]; } catch (Exception __error) { //如果需要記錄錯(cuò)誤日志的,可以記錄到這里,我這里沒(méi)有加 //log.Error("功能介紹GetCountdownAddedSecond:" + __error.Message); if (nCountdownCurrentIndex > m_snIntervalSecond.Length - 1) { nCountdownCurrentIndex = m_snIntervalSecond.Length - 1; } return m_snIntervalSecond[nCountdownCurrentIndex]; } } } }
這個(gè)功能的需求是:業(yè)務(wù)部門(mén)需要監(jiān)控當(dāng)前頁(yè)面的曝光率,所以需要用概率去判斷當(dāng)前的曝光代碼如何在頁(yè)面上交替顯示,起初是曝光率為50%,所以數(shù)組中直接就是new int[] { 0, 1},后來(lái)改成75%,就是上面的代碼,所以這樣既可以監(jiān)控曝光,有可以控制曝光代碼。
前臺(tái)調(diào)用是用AJAX方式:
說(shuō)明:等于1,將曝光代碼添加到頁(yè)面,否則不加
1
$.post("/Topic/GetCountdownAddedSecond", function (data) { if (data) { if (data.num == 1) { var img_html = "<img src="https://d_directed_treatment ="display:none;">"; $("#adver").html(img_html); } } }, "json");
【c#實(shí)現(xiàn)輪詢算法實(shí)例代碼】相關(guān)文章:
C#實(shí)現(xiàn)協(xié)同過(guò)濾算法的實(shí)例代碼06-19
c#實(shí)現(xiàn)sunday算法實(shí)例08-07
快速排序算法及C#版的實(shí)現(xiàn)示例07-03
C語(yǔ)言中實(shí)現(xiàn)KMP算法實(shí)例08-09