网站首页 语言 会计 互联网计算机 医学 学历 职场 文艺体育 范文
当前位置:学识谷 > 计算机 > C语言

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

栏目: C语言 / 发布于: / 人气:1.95W

轮询算法是最简单的一种负载均衡算法。它的原理是把来自用户的请求轮流分配给内部的服务器:从服务器1开始,直到服务器N,然后重新开始循环。下面小编为大家整理了c#实现轮询算法实例代码,希望能帮到大家!

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");