一、概念
- 活跃数
- 集群中各实例未处理的请求数。
- 最小活跃数
- 集群中各个实例,哪个实例未处理的请求数据最小,就称之为最小活跃数。
二、场景与设计思路
- 场景
- 以获取微服务地址为场景。
- 设计思路
- 初始化微服务地址,并初始化活跃数。
- 获取字典或集合中活跃数最小的值,如果获取的值有多个,说明活跃数是相同,必须随机出一个地址后,活跃数并且加1。
- 获取到地址后,必须将该地址的活跃数减1。
三、实现
- 新建抽象类--AbstractLeastActive
public abstract class AbstractLeastActive { #region 变量 /// <summary> /// 字典 /// </summary> public ConcurrentDictionary<string, int> keyValuePairs = new ConcurrentDictionary<string, int>(); /// <summary> /// 相同编号的数据集合 /// </summary> protected List<string> list = new List<string>(); #endregion #region 虚函数 /// <summary> /// 筛选最小编号的数据 /// </summary> protected void FilterMinValue() { int number = int.MaxValue; foreach (var item in keyValuePairs) { if (number >= item.Value) { if (number == item.Value) { number = item.Value; list.Add(item.Key); continue; } list.Clear(); number = item.Value; list.Add(item.Key); } } } /// <summary> /// 随机集合中的数据 /// </summary> protected string RandomValue() { Random random = new Random(); var num = random.Next(list.Count); return list[num]; } /// <summary> /// 活跃数加1 /// </summary> /// <param name="key">key值</param> protected void AddActive(string key) { keyValuePairs.TryUpdate(key, keyValuePairs[key]+1, keyValuePairs[key]); } #endregion /// <summary> /// 释放编号 /// </summary> /// <param name="key"></param> public abstract void Dispose(string key); /// <summary> /// 获取最小活跃数 /// </summary> /// <returns></returns> public abstract string GetValue();
- 新建实现类--LeastActive
public class LeastActive : AbstractLeastActive { /// <summary> /// 获取最小活跃数据 /// </summary> /// <returns></returns> public override string GetValue() { string value = ""; //筛选数据 this.FilterMinValue(); if (this.list.Count == 1) { value = this.list[0]; //活跃数加1 this.AddActive(value); return value; } else if (this.list.Count > 1) { value = this.RandomValue(); //活跃数加1 this.AddActive(value); return value; } return value; } /// <summary> /// 最小活跃数据释放 /// </summary> /// <param name="key"></param> public override void Dispose(string key) { keyValuePairs.TryUpdate(key, keyValuePairs[key] - 1, keyValuePairs[key]); } }
- 新建单元测试
private AbstractLeastActive abstractLeastActive = new LeastActive(); [Fact] public void Test1() { abstractLeastActive.keyValuePairs.TryAdd("http://localhost:8080", 0); abstractLeastActive.keyValuePairs.TryAdd("http://localhost:8082", 1); abstractLeastActive.keyValuePairs.TryAdd("http://localhost:8081", -1); abstractLeastActive.keyValuePairs.TryAdd("http://localhost:8083", -1); string value = abstractLeastActive.GetValue(); abstractLeastActive.Dispose(value); Assert.Equal("http://localhost:8083", value); }
四、代码下载
CSDN:https://download.csdn.net/download/Fu_Shi_rong/87435602 Git:https://gitee.com/Fu_Shi_rong/gcnf.algorithm
标签:key,负载,均衡,list,value,算法,keyValuePairs,public,string From: https://blog.51cto.com/fushirong/6049665