這兩天做東西,業務上有個特殊的需求,在用戶訪問頁面的時候,針對某一行代碼進行控制,按照概率來進行顯示,我做的是針對當前頁面的曝光進行處理,曝光代碼是第三方的,頁面上只要有這段代碼就算是執行了這段曝光代碼,所以才寫了這個輪詢的一個方法,這個方法可以根據自己的需求修改,下面我把這個方法全部帖出來:
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方式:
說明:等於1,將曝光代碼添加到頁面,否則不加
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 (未經允許嚴禁用於商業用途!)