C#实现限流&负载均衡算法

限流算法

实现技术:WCF

测试工具:Postman的Runner工具

服务类:

        /// 
        /// 阈值,每秒钟最多访问16次
        /// 
        private static int QPS = 16;

        /// 
        /// 重置访问次数的时间间隔
        /// 
        /// 1秒 = 1000号码,1毫秒=10000ticks.
        private static int TIME_WINDOWS = 1 * 10000 * 1000;

        /// 
        /// 起始时间.
        /// 
        private static long START_TIME = DateTime.Now.Ticks;

        /// 
        /// 计数器.
        /// 
        private static AtomicInteger REC_COUNT = new AtomicInteger();

        /// 
        /// 验证请求次数是否超过限制.
        /// 
        /// 
        private bool TryAcquire()
        {
            if (DateTime.Now.Ticks - Service1.START_TIME > TIME_WINDOWS)
            {
                // 每隔1s重置一次计数器
                Service1.REC_COUNT.Set(0);
                Service1.START_TIME = DateTime.Now.Ticks;
            }

            return Service1.REC_COUNT.IncrementAndGet() < Service1.QPS;
        }

        /// 
        /// 一种简单的限制流量的算法.
        /// 
        /// 

        public string LimitRequest()
        {
            string msg = string.Empty;
            try
            {
                if (TryAcquire())
                {
                    msg = DateTime.Now.ToString() + ":请求成功";
                    Debug.WriteLine(msg);
                    return msg;
                }
                else
                {
                    // 请求超时
                    throw new WebFaultException(System.Net.HttpStatusCode.GatewayTimeout);
                }
            }
            catch (Exception ex)
            {
                // 服务器错误
                Debug.WriteLine(DateTime.Now.ToString() + ":" + ex.Message);
                throw ex;
            }
        }

辅助类:

    public class AtomicInteger
    {
        public int count { get; set; }

        /// 
        /// 设置次数.
        /// 
        /// 
        public void Set(int count)
        {
            this.count = count;
        }

        /// 
        /// 自增并返回次数.
        /// 
        /// 
        public int IncrementAndGet()
        {
            return count++;
        }
    }

负载均衡

实现技术:WCF

测试工具:Postman的Runner工具

服务类:

        /// 
        /// 服务器列表.
        /// 
        private List _service_map = new List()
        {
            new IPAddressRight("192.168.1.1", 2 ),
            new IPAddressRight("192.168.1.2", 2 ),
            new IPAddressRight("192.168.1.3", 2 ),
            new IPAddressRight("192.168.1.4", 4 ),
        };

        /// 
        /// 访问下标.
        /// 
        private int index = 0;

        /// 
        /// 负载均衡加权算法.
        /// 
        /// 
        public string LoadBalance()
        {
            List list_temp = new List();
            for (int i = 0; i < _service_map.Count; i++)
            {
                for (int j = 0; j < _service_map.ElementAt(i).Right; j++)
                {
                    // 优先级高的在列表中的数量就多
                    list_temp.Add(_service_map.ElementAt(i).Address);
                }
            }
            
            if(index == list_temp.Count)
            {
                index = 0;
            }
            
            // 被调用的服务器地址
            string invokeServiceName = list_temp.ElementAt(index);
            int indexOfServiceMap = this._service_map.FindIndex(m => m.Address.Equals(invokeServiceName));
            if(indexOfServiceMap >= 0)
            {
                this._service_map.ElementAt(indexOfServiceMap).Count++;
            }

            // 日志输出
            Debug.WriteLine(DateTime.Now.ToString() + ":调用" + invokeServiceName);
            StringBuilder builder = new StringBuilder();

            Debug.WriteLine("统计:");
            for (int i = 0; i < this._service_map.Count; i++)
            {
                builder.AppendFormat("调用{0},{1}次\r\n", this._service_map[i].Address, this._service_map[i].Count);
            }

            Debug.WriteLine(builder.ToString());
            index++;
            return invokeServiceName + "\r\n" + builder.ToString();
        }

辅助类:

    public class IPAddressRight
    {
        public IPAddressRight(string address, int right)
        {
            this.Address = address;
            this.Right = right;
        }

        /// 
        /// 地址.
        /// 
        public string Address { get; set; }

        /// 
        /// 权限级别.
        /// 
        public int Right { get; set; }

        /// 
        /// 调用次数.
        /// 
        public int Count { get; set; }
    }

参考:一篇有趣的负载均衡算法实现 | 未读代码

你可能感兴趣的:(Web应用,服务器,c#,算法)