這兩天作東西,業務上有個特殊的需求,在用戶訪問頁面的時候,針對某一行代碼進行控制,按照機率來進行顯示,我作的是針對當前頁面的曝光進行處理,曝光代碼是第三方的,頁面上只要有這段代碼就算是執行了這段曝光代碼,因此才寫了這個輪詢的一個方法,這個方法能夠根據本身的需求修改,下面我把這個方法所有帖出來:html
CacheSlidingExpirationHour:時間,緩存時間2小時
CountdownCurrentIndexCacheName:緩存名稱
log:日誌
m_objCountdownCurrentIndexLock::當前對象
m_snIntervalSecond:定義一個數組,能夠視爲機率值
說明:0,1,1,1 數據中存了4個數,咱們設爲總的機率爲100%,每一個表明25%,因此如今我設置的是當前的機率爲75%
存如緩存的是數據的索引,取的時候也取的索引,方法返回索引,轉成int類型
1 public class CountdownHelper 2 { 3 private const int CacheSlidingExpirationHour = 2; 4 private const string CountdownCurrentIndexCacheName = "OnlineMeetingCountdownCurrentIndex"; 5 private static IAppLog log = AppLoggerManager.GetLogger(typeof(CountdownHelper)); 6 private static Cache m_cache = HttpContext.Current.Cache; 7 private static object m_objCountdownCurrentIndexLock = new object(); 8 private static int[] m_snIntervalSecond = new int[] { 0, 1 , 1 , 1}; //1顯示 0不顯示 9 10 public CountdownHelper() 11 { 12 } 13 14 public int GetCountdownAddedSecond() 15 { 16 lock (m_objCountdownCurrentIndexLock) 17 { 18 int nCountdownCurrentIndex = 0; 19 20 try 21 { 22 object objCountdownCurrentIndex = m_cache[CountdownCurrentIndexCacheName]; 23 if (objCountdownCurrentIndex == null) 24 { 25 //若是須要加緩存的,就用下面的 26 //m_cache.Insert(CountdownCurrentIndexCacheName, 1, null, Cache.NoAbsoluteExpiration, TimeSpan.FromHours(CacheSlidingExpirationHour), CacheItemPriority.NotRemovable, null); 27 //不用加緩存的用下面的 28 m_cache.Insert(CountdownCurrentIndexCacheName, 1, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null); 29 } 30 else 31 { 32 nCountdownCurrentIndex = (int)objCountdownCurrentIndex; 33 34 if (nCountdownCurrentIndex == m_snIntervalSecond.Length - 1) 35 { 36 m_cache[CountdownCurrentIndexCacheName] = 0; 37 } 38 else 39 { 40 m_cache[CountdownCurrentIndexCacheName] = nCountdownCurrentIndex + 1; 41 } 42 } 43 44 return m_snIntervalSecond[nCountdownCurrentIndex]; 45 } 46 catch (Exception __error) 47 { 48 //若是須要記錄錯誤日誌的,能夠記錄到這裏,我這裏沒有加 49 //log.Error("功能介紹GetCountdownAddedSecond:" + __error.Message); 50 if (nCountdownCurrentIndex > m_snIntervalSecond.Length - 1) 51 { 52 nCountdownCurrentIndex = m_snIntervalSecond.Length - 1; 53 } 54 return m_snIntervalSecond[nCountdownCurrentIndex]; 55 } 56 } 57 } 58 59 }
這個功能的需求是:業務部門須要監控當前頁面的曝光率,因此須要用機率去判斷當前的曝光代碼如何在頁面上交替顯示,起初是曝光率爲50%,因此數組中直接就是new int[] { 0, 1},後來改爲75%,就是上面的代碼,因此這樣既能夠監控曝光,有能夠控制曝光代碼。算法
前臺調用是用AJAX方式:json
說明:等於1,將曝光代碼添加到頁面,不然不加c#
1 <div id="adver"></div>
1 <!--輪詢曝光--> 2 $.post("/Topic/GetCountdownAddedSecond", function (data) { 3 if (data) { 4 if (data.num == 1) { 5 var img_html = "<img src=\"https://d_directed_treatment =?\ment\" style=\"display:none;\">"; 6 $("#adver").html(img_html); 7 } 8 } 9 }, "json");
版權聲明:歡迎轉載,可是看在我辛勤勞動的份上,請註明來源:http://www.cnblogs.com/zhangpengnike/p/5546046.html (未經容許嚴禁用於商業用途!)數組