前言:高并发对咱们来讲应该都不陌生,特别想淘宝秒杀,竞价等等,使用的很是多,如何在高并发的状况下,使用限流,保证业务的进行呢。如下是一个实例,不喜勿喷!算法
整体思路:数组
1. 用一个环形来表明经过的请求容器。服务器
2. 用一个指针指向当前请求所到的位置索引,来判断当前请求时间和当前位置上次请求的时间差,依此来判断是否被限制。并发
3. 若是请求经过,则当前指针向前移动一个位置,不经过则不移动位置高并发
4. 重复以上步骤 直到永远.......测试
如下代码的核心思路是这样的:指针当前位置的时间元素和当前时间的差来决定是否容许这次请求,这样经过的请求在时间上表现的比较平滑。spa
实例使用.net写的,仅供参考,了解思路和原理,须要者彻底能够用其余方式语言来实现,很简单:.net
public class LimitService { /// <summary> /// 当前指针位置 /// </summary> public int currentIndex = 0; //限制的时间的秒数,即:x秒容许多少请求 public int limitTimeSencond = 1; /// <summary> /// 请求环的数组容器 /// </summary> public DateTime?[] requstRing { get; set; } = null; /// <summary> /// 容器改变或者移动指针时的锁; /// </summary> object obj = new object(); public LimitService(int countPerSecond, int _limitTimeSencond) { limitTimeSencond = _limitTimeSencond; requstRing = new DateTime?[countPerSecond]; } /// <summary> /// 程序是否能够继续 /// </summary> /// <returns></returns> public bool IsContinue() { lock (obj) { var currentNode = requstRing[currentIndex]; if (currentNode != null && currentNode.Value.AddSeconds(limitTimeSencond) > DateTime.Now) { return false; } //当前节点设置为当前时间 requstRing[currentIndex] = DateTime.Now; //指针移动一个位置 MoveNextIndex(ref currentIndex); } return true; } /// <summary> /// 改变每秒能够经过的请求数 /// </summary> /// <param name="countPerSecond"></param> /// <returns></returns> public bool ChangeCountPerSecond(int countPerSecond) { lock (obj) { requstRing = new DateTime?[countPerSecond]; currentIndex = 0; } return true; } /// <summary> /// 指针往前移动一个位置 /// </summary> /// <param name="currentIndex"></param> public void MoveNextIndex (ref int currentIndex) { if(currentIndex!= requstRing.Length - 1) { currentIndex = currentIndex + 1; } else { currentIndex = 0; } }
测试程序以下:pwa
1 public class Program 2 { 3 static LimitService l = new LimitService(1000, 1); 4 public static void Main(string[] args) 5 { 6 7 int threadCount = 50; 8 9 while (threadCount >= 0) 10 { 11 Thread t = new Thread(s => { 12 Limit(); 13 14 }); 15 16 t.Start(); 17 18 threadCount--; 19 } 20 21 Console.ReadKey(); 22 } 23 24 public static void Limit() 25 { 26 int i = 0; 27 int okCount = 0; 28 int noCount = 0; 29 Stopwatch w = new Stopwatch(); 30 w.Start(); 31 while (i < 1000000) 32 { 33 var ret = l.IsContinue(); 34 if (ret) 35 { 36 okCount++; 37 } 38 else 39 { 40 noCount++; 41 } 42 i++; 43 } 44 w.Stop(); 45 Console.WriteLine($"共用{w.ElapsedMilliseconds},容许:{okCount}, 拦截:{noCount}"); 46 } 47 }
测试结果:线程
最大用时7秒,共处理请求1000000*50=50000000 次
并未发生GC操做,内存使用率很是低,每秒处理 300万次+请求 。以上程序修改成10个线程,大约用时4秒以内
若是是强劲的服务器或者线程数较少状况下处理速度将会更快!!!
以上就是测试的限制高并发的一种简单方案,固然还有其余方式好比:令牌桶算法,漏桶算法等等,能够去研究下!
以上仅为我的观点,若是错误,请你们指针,谢谢!