C语言 百分网手机站

c#实现轮询算法实例代码

时间:2020-09-22 19:00:32 C语言 我要投稿

c#实现轮询算法实例代码

  轮询算法是最简单的一种负载均衡算法。它的原理是把来自用户的请求轮流分配给内部的服务器:从服务器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 = 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)  {  //如果需要记录错误日志的,可以记录到这里,我这里没有加  //log.Error("功能介绍GetCountdownAddedSecond:" + __error.Message);  if (nCountdownCurrentIndex > m_snIntervalSecond.Length - 1)  {  nCountdownCurrentIndex = m_snIntervalSecond.Length - 1;  }  return m_snIntervalSecond[nCountdownCurrentIndex];  } } } }

  这个功能的需求是:业务部门需要监控当前页面的曝光率,所以需要用概率去判断当前的曝光代码如何在页面上交替显示,起初是曝光率为50%,所以数组中直接就是new int[] { 0, 1},后来改成75%,就是上面的代码,所以这样既可以监控曝光,有可以控制曝光代码。

  前台调用是用AJAX方式:

  说明:等于1,将曝光代码添加到页面,否则不加

  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#实现轮询算法实例代码】相关文章:

C#实现协同过滤算法的实例代码10-20

KMP算法的C#实现方法10-24

C语言中实现KMP算法实例11-19

快速排序算法及C#版的实现示例09-30

C语言插入排序算法及实例代码10-08

C语言奇偶排序算法详解及实例代码10-04

C#数据结构之循环链表的实例代码10-07

C语言实现归并排序算法实例11-21

冒泡排序算法原理及JAVA实现代码方法12-02