翼度科技»论坛 编程开发 .net 查看内容

ASP.NET Core中如何限制响应发送速率(不是调用频率)

10

主题

10

帖子

30

积分

新手上路

Rank: 1

积分
30
前言

ASP.NET Core中有很多RateLimit组件,.NET 7甚至推出了官方版本。不过这些组件的主要目标是限制客户端访问服务的频率,在HTTP服务器崩溃前主动拒绝部分请求。如果请求没有被拒绝服务会尽可能调用资源尽快处理。
现在有一个问题,有什么办法限制响应的发送速率吗?这在一些需要长时间传输流式数据的情况时很有用,避免少量请求耗尽网络带宽,尽可能同时服务更多请求。
Tip

本文节选自我的新书《C#与.NET6 开发从入门到实践》12.11 流量控制。实现方式偏向知识讲解和教学,不保证组件稳定性,不建议直接在产品中使用。有关新书的更多介绍欢迎查看《C#与.NET6 开发从入门到实践》预售,作者亲自来打广告了!

正文

用过百度网盘的人应该都深有体会,如果没有会员,下载速度会非常慢。实现这种效果的方法有两种:控制TCP协议的滑动窗口大小;控制响应流的写入大小和频率。偏向系统底层的流量控制软件因为无法干涉软件中的流,所以一般会直接控制内核TCP协议的滑动窗口大小;而下载软件等客户端应用通常直接控制流的写入和读取,此时TCP协议的拥塞控制算法会自动调整滑动窗口大小。这种流量控制对提供大型多媒体资源的应用(例如在线视频网站)非常重要,能防止一个请求的响应占用太多带宽影响其他请求的响应发送。
ASP.NET Core并没有原生提供相关功能,Nuget上也没有找到相关的程序包(截止截稿)。但其实利用ASP.NET Core提供的接口,是可以实现这个功能的。笔者以ASP.NET Core的响应压缩中间件为蓝本,实现了一个简单的响应限流中间件。
编写节流组件

支持限速的基础流
  1. using System;
  2. namespace AccessControlElementary;
  3. /// <summary>
  4. /// 支持流量控制的流
  5. /// </summary>
  6. public class ThrottlingStream : Stream
  7. {
  8.     /// <summary>
  9.     /// 用于指定每秒可传输的无限字节数的常数。
  10.     /// </summary>
  11.     public const long Infinite = 0;
  12.     #region Private members
  13.     /// <summary>
  14.     /// 基础流
  15.     /// </summary>
  16.     private readonly Stream _baseStream;
  17.     /// <summary>
  18.     /// 每秒可通过基础流传输的最大字节数。
  19.     /// </summary>
  20.     private long _maximumBytesPerSecond;
  21.     /// <summary>
  22.     /// 自上次限制以来已传输的字节数。
  23.     /// </summary>
  24.     private long _byteCount;
  25.     /// <summary>
  26.     /// 最后一次限制的开始时间(毫秒)。
  27.     /// </summary>
  28.     private long _start;
  29.     #endregion
  30.     #region Properties
  31.     /// <summary>
  32.     /// 获取当前毫秒数。
  33.     /// </summary>
  34.     /// <value>当前毫秒数。</value>
  35.     protected long CurrentMilliseconds => Environment.TickCount;
  36.     /// <summary>
  37.     /// 获取或设置每秒可通过基础流传输的最大字节数。
  38.     /// </summary>
  39.     /// <value>每秒最大字节数。</value>
  40.     public long MaximumBytesPerSecond
  41.     {
  42.         get => _maximumBytesPerSecond;
  43.         set
  44.         {
  45.             if (MaximumBytesPerSecond != value)
  46.             {
  47.                 _maximumBytesPerSecond = value;
  48.                 Reset();
  49.             }
  50.         }
  51.     }
  52.     /// <summary>
  53.     /// 获取一个值,该值指示当前流是否支持读取。
  54.     /// </summary>
  55.     /// <returns>如果流支持读取,则为true;否则为false。</returns>
  56.     public override bool CanRead => _baseStream.CanRead;
  57.     /// <summary>
  58.     /// 获取估算的流当前的比特率(单位:bps)。
  59.     /// </summary>
  60.     public long CurrentBitsPerSecond { get; protected set; }
  61.     /// <summary>
  62.     /// 获取一个值,该值指示当前流是否支持定位。
  63.     /// </summary>
  64.     /// <value></value>
  65.     /// <returns>如果流支持定位,则为true;否则为false。</returns>
  66.     public override bool CanSeek => _baseStream.CanSeek;
  67.     /// <summary>
  68.     /// 获取一个值,该值指示当前流是否支持写入。
  69.     /// </summary>
  70.     /// <value></value>
  71.     /// <returns>如果流支持写入,则为true;否则为false。</returns>
  72.     public override bool CanWrite => _baseStream.CanWrite;
  73.     /// <summary>
  74.     /// 获取流的长度(以字节为单位)。
  75.     /// </summary>
  76.     /// <value></value>
  77.     /// <returns>一个long值,表示流的长度(字节)。</returns>
  78.     /// <exception cref="T:System.NotSupportedException">基础流不支持定位。</exception>
  79.     /// <exception cref="T:System.ObjectDisposedException">方法在流关闭后被调用。</exception>
  80.     public override long Length => _baseStream.Length;
  81.     /// <summary>
  82.     /// 获取或设置当前流中的位置。
  83.     /// </summary>
  84.     /// <value></value>
  85.     /// <returns>流中的当前位置。</returns>
  86.     /// <exception cref="T:System.IO.IOException">发生I/O错误。</exception>
  87.     /// <exception cref="T:System.NotSupportedException">基础流不支持定位。</exception>
  88.     /// <exception cref="T:System.ObjectDisposedException">方法在流关闭后被调用。</exception>
  89.     public override long Position
  90.     {
  91.         get => _baseStream.Position;
  92.         set => _baseStream.Position = value;
  93.     }
  94.     #endregion
  95.     #region Ctor
  96.     /// <summary>
  97.     /// 使用每秒可传输无限字节数的常数初始化 <see cref="T:ThrottlingStream"/> 类的新实例。
  98.     /// </summary>
  99.     /// <param name="baseStream">基础流。</param>
  100.     public ThrottlingStream(Stream baseStream)
  101.         : this(baseStream, Infinite) { }
  102.     /// <summary>
  103.     /// 初始化 <see cref="T:ThrottlingStream"/> 类的新实例。
  104.     /// </summary>
  105.     /// <param name="baseStream">基础流。</param>
  106.     /// <param name="maximumBytesPerSecond">每秒可通过基础流传输的最大字节数。</param>
  107.     /// <exception cref="ArgumentNullException">当 <see cref="baseStream"/> 是null引用时抛出。</exception>
  108.     /// <exception cref="ArgumentOutOfRangeException">当 <see cref="maximumBytesPerSecond"/> 是负数时抛出.</exception>
  109.     public ThrottlingStream(Stream baseStream, long maximumBytesPerSecond)
  110.     {
  111.         if (maximumBytesPerSecond < 0)
  112.         {
  113.             throw new ArgumentOutOfRangeException(nameof(maximumBytesPerSecond),
  114.                 maximumBytesPerSecond, "The maximum number of bytes per second can't be negatie.");
  115.         }
  116.         _baseStream = baseStream ?? throw new ArgumentNullException(nameof(baseStream));
  117.         _maximumBytesPerSecond = maximumBytesPerSecond;
  118.         _start = CurrentMilliseconds;
  119.         _byteCount = 0;
  120.     }
  121.     #endregion
  122.     #region Public methods
  123.     /// <summary>
  124.     /// 清除此流的所有缓冲区,并将所有缓冲数据写入基础设备。
  125.     /// </summary>
  126.     /// <exception cref="T:System.IO.IOException">发生I/O错误。</exception>
  127.     public override void Flush() => _baseStream.Flush();
  128.     /// <summary>
  129.     /// 清除此流的所有缓冲区,并将所有缓冲数据写入基础设备。
  130.     /// </summary>
  131.     /// <exception cref="T:System.IO.IOException">发生I/O错误。</exception>
  132.     public override Task FlushAsync(CancellationToken cancellationToken) => _baseStream.FlushAsync(cancellationToken);
  133.     /// <summary>
  134.     /// 从当前流中读取字节序列,并将流中的位置前进读取的字节数。
  135.     /// </summary>
  136.     /// <param name="buffer">字节数组。当此方法返回时,缓冲区包含指定的字节数组,其值介于offset和(offset+count-1)之间,由从当前源读取的字节替换。</param>
  137.     /// <param name="offset">缓冲区中从零开始的字节偏移量,开始存储从当前流中读取的数据。</param>
  138.     /// <param name="count">从当前流中读取的最大字节数。</param>
  139.     /// <returns>
  140.     /// 读入缓冲区的字节总数。如果许多字节当前不可用,则该值可以小于请求的字节数;如果已到达流的结尾,则该值可以小于零(0)。
  141.     /// </returns>
  142.     /// <exception cref="T:System.ArgumentException">偏移量和计数之和大于缓冲区长度。</exception>
  143.     /// <exception cref="T:System.ObjectDisposedException">方法在流关闭后被调用。</exception>
  144.     /// <exception cref="T:System.NotSupportedException">基础流不支持读取。 </exception>
  145.     /// <exception cref="T:System.ArgumentNullException">缓冲区为null。</exception>
  146.     /// <exception cref="T:System.IO.IOException">发生I/O错误。</exception>
  147.     /// <exception cref="T:System.ArgumentOutOfRangeException">偏移量或读取的最大字节数为负。</exception>
  148.     public override int Read(byte[] buffer, int offset, int count)
  149.     {
  150.         Throttle(count);
  151.         return _baseStream.Read(buffer, offset, count);
  152.     }
  153.     /// <summary>
  154.     /// 从当前流中读取字节序列,并将流中的位置前进读取的字节数。
  155.     /// </summary>
  156.     /// <param name="buffer">字节数组。当此方法返回时,缓冲区包含指定的字节数组,其值介于offset和(offset+count-1)之间,由从当前源读取的字节替换。</param>
  157.     /// <param name="offset">缓冲区中从零开始的字节偏移量,开始存储从当前流中读取的数据。</param>
  158.     /// <param name="count">从当前流中读取的最大字节数。</param>
  159.     /// <param name="cancellationToken">取消令牌。</param>
  160.     /// <returns>
  161.     /// 读入缓冲区的字节总数。如果许多字节当前不可用,则该值可以小于请求的字节数;如果已到达流的结尾,则该值可以小于零(0)。
  162.     /// </returns>
  163.     /// <exception cref="T:System.ArgumentException">偏移量和计数之和大于缓冲区长度。</exception>
  164.     /// <exception cref="T:System.ObjectDisposedException">方法在流关闭后被调用。</exception>
  165.     /// <exception cref="T:System.NotSupportedException">基础流不支持读取。 </exception>
  166.     /// <exception cref="T:System.ArgumentNullException">缓冲区为null。</exception>
  167.     /// <exception cref="T:System.IO.IOException">发生I/O错误。</exception>
  168.     /// <exception cref="T:System.ArgumentOutOfRangeException">偏移量或读取的最大字节数为负。</exception>
  169.     public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  170.     {
  171.         return await ReadAsync(buffer.AsMemory(offset, count), cancellationToken);
  172.     }
  173.     /// <summary>
  174.     /// 从当前流中读取字节序列,并将流中的位置前进读取的字节数。
  175.     /// </summary>
  176.     /// <param name="buffer">内存缓冲区。当此方法返回时,缓冲区包含读取的数据。</param>
  177.     /// <param name="cancellationToken">取消令牌。</param>
  178.     /// <returns>
  179.     /// 读入缓冲区的字节总数。如果许多字节当前不可用,则该值可以小于请求的字节数;如果已到达流的结尾,则该值可以小于零(0)。
  180.     /// </returns>
  181.     /// <exception cref="T:System.ArgumentException">偏移量和计数之和大于缓冲区长度。</exception>
  182.     /// <exception cref="T:System.ObjectDisposedException">方法在流关闭后被调用。</exception>
  183.     /// <exception cref="T:System.NotSupportedException">基础流不支持读取。 </exception>
  184.     /// <exception cref="T:System.ArgumentNullException">缓冲区为null。</exception>
  185.     /// <exception cref="T:System.IO.IOException">发生I/O错误。</exception>
  186.     /// <exception cref="T:System.ArgumentOutOfRangeException">偏移量或读取的最大字节数为负。</exception>
  187.     public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
  188.     {
  189.         await ThrottleAsync(buffer.Length, cancellationToken);
  190.         return await _baseStream.ReadAsync(buffer, cancellationToken);
  191.     }
  192.     /// <summary>
  193.     /// 设置当前流中的位置。
  194.     /// </summary>
  195.     /// <param name="offset">相对于参考点的字节偏移量。</param>
  196.     /// <param name="origin">类型为<see cref="T:System.IO.SeekOrigin"/>的值,指示用于获取新位置的参考点。</param>
  197.     /// <returns>
  198.     /// 当前流中的新位置。
  199.     /// </returns>
  200.     /// <exception cref="T:System.IO.IOException">发生I/O错误。</exception>
  201.     /// <exception cref="T:System.NotSupportedException">基础流不支持定位,例如流是从管道或控制台输出构造的。</exception>
  202.     /// <exception cref="T:System.ObjectDisposedException">方法在流关闭后被调用。</exception>
  203.     public override long Seek(long offset, SeekOrigin origin)
  204.     {
  205.         return _baseStream.Seek(offset, origin);
  206.     }
  207.     /// <summary>
  208.     /// 设置当前流的长度。
  209.     /// </summary>
  210.     /// <param name="value">当前流的所需长度(字节)。</param>
  211.     /// <exception cref="T:System.NotSupportedException">基础流不支持写入和定位,例如流是从管道或控制台输出构造的。</exception>
  212.     /// <exception cref="T:System.IO.IOException">发生I/O错误。</exception>
  213.     /// <exception cref="T:System.ObjectDisposedException">方法在流关闭后被调用。</exception>
  214.     public override void SetLength(long value)
  215.     {
  216.         _baseStream.SetLength(value);
  217.     }
  218.     /// <summary>
  219.     /// 将字节序列写入当前流,并按写入的字节数前进此流中的当前位置。
  220.     /// </summary>
  221.     /// <param name="buffer">字节数组。此方法将要写入当前流的字节从缓冲区复制到当前流。</param>
  222.     /// <param name="offset">缓冲区中从零开始向当前流复制字节的字节偏移量。</param>
  223.     /// <param name="count">要写入当前流的字节数。</param>
  224.     /// <exception cref="T:System.IO.IOException">发生I/O错误。</exception>
  225.     /// <exception cref="T:System.NotSupportedException">基础流不支持写入。</exception>
  226.     /// <exception cref="T:System.ObjectDisposedException">方法在流关闭后被调用。</exception>
  227.     /// <exception cref="T:System.ArgumentNullException">缓冲区为null。</exception>
  228.     /// <exception cref="T:System.ArgumentException">偏移量和写入字节数之和大于缓冲区长度。</exception>
  229.     /// <exception cref="T:System.ArgumentOutOfRangeException">偏移量或写入字节数为负。</exception>
  230.     public override void Write(byte[] buffer, int offset, int count)
  231.     {
  232.         Throttle(count);
  233.         _baseStream.Write(buffer, offset, count);
  234.     }
  235.     /// <summary>
  236.     /// 将字节序列写入当前流,并按写入的字节数前进此流中的当前位置。
  237.     /// </summary>
  238.     /// <param name="buffer">字节数组。此方法将要写入当前流的字节从缓冲区复制到当前流。</param>
  239.     /// <param name="offset">缓冲区中从零开始向当前流复制字节的字节偏移量。</param>
  240.     /// <param name="count">要写入当前流的字节数。</param>
  241.     /// <param name="cancellationToken">取消令牌。</param>
  242.     /// <exception cref="T:System.IO.IOException">发生I/O错误。</exception>
  243.     /// <exception cref="T:System.NotSupportedException">基础流不支持写入。</exception>
  244.     /// <exception cref="T:System.ObjectDisposedException">方法在流关闭后被调用。</exception>
  245.     /// <exception cref="T:System.ArgumentNullException">缓冲区为null。</exception>
  246.     /// <exception cref="T:System.ArgumentException">偏移量和写入字节数之和大于缓冲区长度。</exception>
  247.     /// <exception cref="T:System.ArgumentOutOfRangeException">偏移量或写入字节数为负。</exception>
  248.     public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  249.     {
  250.         await WriteAsync(buffer.AsMemory(offset, count), cancellationToken);
  251.     }
  252.     /// <summary>
  253.     /// 将内存缓冲区写入当前流,并按写入的字节数前进此流中的当前位置。
  254.     /// </summary>
  255.     /// <param name="buffer">内存缓冲区。此方法将要写入当前流的字节从缓冲区复制到当前流。</param>
  256.     /// <param name="cancellationToken">取消令牌。</param>
  257.     /// <exception cref="T:System.IO.IOException">发生I/O错误。</exception>
  258.     /// <exception cref="T:System.NotSupportedException">基础流不支持写入。</exception>
  259.     /// <exception cref="T:System.ObjectDisposedException">方法在流关闭后被调用。</exception>
  260.     /// <exception cref="T:System.ArgumentNullException">缓冲区为null。</exception>
  261.     /// <exception cref="T:System.ArgumentException">偏移量和写入字节数之和大于缓冲区长度。</exception>
  262.     /// <exception cref="T:System.ArgumentOutOfRangeException">偏移量或写入字节数为负。</exception>
  263.     public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
  264.     {
  265.         await ThrottleAsync(buffer.Length, cancellationToken);
  266.         await _baseStream.WriteAsync(buffer, cancellationToken);
  267.     }
  268.     /// <summary>
  269.     /// 返回一个表示当前<see cref="T:System.Object" />的<see cref="T:System.String" />。
  270.     /// </summary>
  271.     /// <returns>
  272.     /// 表示当前<see cref="T:System.Object" />的<see cref="T:System.String" />。
  273.     /// </returns>
  274.     public override string ToString()
  275.     {
  276.         return _baseStream.ToString()!;
  277.     }
  278.     #endregion
  279.     #region Protected methods
  280.     /// <summary>
  281.     /// 如果比特率大于最大比特率,尝试限流
  282.     /// </summary>
  283.     /// <param name="bufferSizeInBytes">缓冲区大小(字节)。</param>
  284.     protected void Throttle(int bufferSizeInBytes)
  285.     {
  286.         var toSleep = CaculateThrottlingMilliseconds(bufferSizeInBytes);
  287.         if (toSleep > 1)
  288.         {
  289.             try
  290.             {
  291.                 Thread.Sleep(toSleep);
  292.             }
  293.             catch (ThreadAbortException)
  294.             {
  295.                 // 忽略ThreadAbortException。
  296.             }
  297.             // 睡眠已经完成,重置限流
  298.             Reset();
  299.         }
  300.     }
  301.     /// <summary>
  302.     /// 如果比特率大于最大比特率,尝试限流。
  303.     /// </summary>
  304.     /// <param name="bufferSizeInBytes">缓冲区大小(字节)。</param>
  305.     /// <param name="cancellationToken">取消令牌。</param>
  306.     protected async Task ThrottleAsync(int bufferSizeInBytes, CancellationToken cancellationToken)
  307.     {
  308.         var toSleep = CaculateThrottlingMilliseconds(bufferSizeInBytes);
  309.         if (toSleep > 1)
  310.         {
  311.             try
  312.             {
  313.                 await Task.Delay(toSleep, cancellationToken);
  314.             }
  315.             catch (TaskCanceledException)
  316.             {
  317.                 // 忽略TaskCanceledException。
  318.             }
  319.             // 延迟已经完成,重置限流。
  320.             Reset();
  321.         }
  322.     }
  323.     /// <summary>
  324.     /// 计算在操作流之前应当延迟的时间(单位:毫秒)。
  325.     /// 更新流当前的比特率。
  326.     /// </summary>
  327.     /// <param name="bufferSizeInBytes">缓冲区大小(字节)。</param>
  328.     /// <returns>应当延迟的时间(毫秒)。</returns>
  329.     protected int CaculateThrottlingMilliseconds(int bufferSizeInBytes)
  330.     {
  331.         int toSleep = 0;
  332.         // 确保缓冲区不为null
  333.         if (bufferSizeInBytes <= 0)
  334.         {
  335.             CurrentBitsPerSecond = 0;
  336.         }
  337.         else
  338.         {
  339.             _byteCount += bufferSizeInBytes;
  340.             long elapsedMilliseconds = CurrentMilliseconds - _start;
  341.             if (elapsedMilliseconds > 0)
  342.             {
  343.                 // 计算当前瞬时比特率
  344.                 var bp = _byteCount * 1000L;
  345.                 var bps = bp / elapsedMilliseconds;
  346.                 var avgBps = bps;
  347.                 //如果bps大于最大bps,返回应当延迟的时间。
  348.                 if (_maximumBytesPerSecond > 0 && bps > _maximumBytesPerSecond)
  349.                 {
  350.                     // 计算延迟时间
  351.                     long wakeElapsed = bp / _maximumBytesPerSecond;
  352.                     var result = (int)(wakeElapsed - elapsedMilliseconds);
  353.                     // 计算平均比特率
  354.                     var div = result / 1000.0;
  355.                     avgBps = (long)(bps / (div == 0 ? 1 : div));
  356.                     if (result > 1)
  357.                     {
  358.                         toSleep = result; ;
  359.                     }
  360.                 }
  361.                 // 更新当前(平均)比特率
  362.                 CurrentBitsPerSecond = (long)(avgBps / 8);
  363.             }
  364.         }
  365.         return toSleep;
  366.     }
  367.     /// <summary>
  368.     /// 将字节数重置为0,并将开始时间重置为当前时间。
  369.     /// </summary>
  370.     protected void Reset()
  371.     {
  372.         long difference = CurrentMilliseconds - _start;
  373.         // 只有在已知历史记录可用时间超过1秒时才重置计数器。
  374.         if (difference > 1000)
  375.         {
  376.             _byteCount = 0;
  377.             _start = CurrentMilliseconds;
  378.         }
  379.     }
  380.     #endregion
  381. }
复制代码
CaculateThrottleMilliseconds 、Throttle和ThrottleAsync是这个流的核心。CaculateThrottleMilliseconds方法负责计算在写入或读取流之前应该延迟多久和更新流当前的传输速率,Throttle和ThrottleAsync方法负责同步和异步延迟。
限流响应正文
  1. using Microsoft.AspNetCore.Http.Features;
  2. using Microsoft.Extensions.Options;
  3. using System.IO.Pipelines;
  4. using System;
  5. namespace AccessControlElementary;
  6. // 自定义的HTTP功能接口,提供获取限流速率设置和当前速率的获取能力
  7. public interface IHttpResponseThrottlingFeature
  8. {
  9.     public long? MaximumBytesPerSecond { get; }
  10.     public long? CurrentBitsPerSecond { get; }
  11. }
  12. // 限流响应正文的实现类,实现了自定义的功能接口
  13. public class ThrottlingResponseBody : Stream, IHttpResponseBodyFeature, IHttpResponseThrottlingFeature
  14. {
  15.     private readonly IHttpResponseBodyFeature _innerBodyFeature;
  16.     private readonly IOptionsSnapshot<ResponseThrottlingOptions> _options;
  17.     private readonly HttpContext _httpContext;
  18.     private readonly Stream _innerStream;
  19.     private ThrottlingStream? _throttlingStream;
  20.     private PipeWriter? _pipeAdapter;
  21.     private bool _throttlingChecked;
  22.     private bool _complete;
  23.     private int _throttlingRefreshCycleCount;
  24.     public ThrottlingResponseBody(IHttpResponseBodyFeature innerBodyFeature, HttpContext httpContext, IOptionsSnapshot<ResponseThrottlingOptions> options)
  25.     {
  26.         _options = options ?? throw new ArgumentNullException(nameof(options));
  27.         _httpContext = httpContext ?? throw new ArgumentNullException(nameof(httpContext));
  28.         _innerBodyFeature = innerBodyFeature ?? throw new ArgumentNullException(nameof(innerBodyFeature));
  29.         _innerStream = innerBodyFeature.Stream;
  30.         _throttlingRefreshCycleCount = 0;
  31.     }
  32.     public override bool CanRead => false;
  33.     public override bool CanSeek => false;
  34.     public override bool CanWrite => _innerStream.CanWrite;
  35.     public override long Length => _innerStream.Length;
  36.     public override long Position
  37.     {
  38.         get => throw new NotSupportedException();
  39.         set => throw new NotSupportedException();
  40.     }
  41.     public Stream Stream => this;
  42.     public PipeWriter Writer
  43.     {
  44.         get
  45.         {
  46.             if (_pipeAdapter == null)
  47.             {
  48.                 _pipeAdapter = PipeWriter.Create(Stream, new StreamPipeWriterOptions(leaveOpen: true));
  49.                 if (_complete)
  50.                 {
  51.                     _pipeAdapter.Complete();
  52.                 }
  53.             }
  54.             return _pipeAdapter;
  55.         }
  56.     }
  57.     public long? MaximumBytesPerSecond => _throttlingStream?.MaximumBytesPerSecond;
  58.     public long? CurrentBitsPerSecond => _throttlingStream?.CurrentBitsPerSecond;
  59.     public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
  60.     public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
  61.     public override void SetLength(long value) => throw new NotSupportedException();
  62.     public override void Write(byte[] buffer, int offset, int count)
  63.     {
  64.         OnWriteAsync().ConfigureAwait(false).GetAwaiter().GetResult();
  65.         if (_throttlingStream != null)
  66.         {
  67.             _throttlingStream.Write(buffer, offset, count);
  68.             _throttlingStream.Flush();
  69.         }
  70.         else
  71.         {
  72.             _innerStream.Write(buffer, offset, count);
  73.         }
  74.     }
  75.     public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  76.     {
  77.         await WriteAsync(buffer.AsMemory(offset, count), cancellationToken);
  78.     }
  79.     public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
  80.     {
  81.         await OnWriteAsync();
  82.         if (_throttlingStream != null)
  83.         {
  84.             await _throttlingStream.WriteAsync(buffer, cancellationToken);
  85.             await _throttlingStream.FlushAsync(cancellationToken);
  86.         }
  87.         else
  88.         {
  89.             await _innerStream.WriteAsync(buffer, cancellationToken);
  90.         }
  91.     }
  92.     public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
  93.     {
  94.         var tcs = new TaskCompletionSource(state: state, TaskCreationOptions.RunContinuationsAsynchronously);
  95.         InternalWriteAsync(buffer, offset, count, callback, tcs);
  96.         return tcs.Task;
  97.     }
  98.     private async void InternalWriteAsync(byte[] buffer, int offset, int count, AsyncCallback? callback, TaskCompletionSource tcs)
  99.     {
  100.         try
  101.         {
  102.             await WriteAsync(buffer.AsMemory(offset, count));
  103.             tcs.TrySetResult();
  104.         }
  105.         catch (Exception ex)
  106.         {
  107.             tcs.TrySetException(ex);
  108.         }
  109.         if (callback != null)
  110.         {
  111.             // Offload callbacks to avoid stack dives on sync completions.
  112.             var ignored = Task.Run(() =>
  113.             {
  114.                 try
  115.                 {
  116.                     callback(tcs.Task);
  117.                 }
  118.                 catch (Exception)
  119.                 {
  120.                     // Suppress exceptions on background threads.
  121.                 }
  122.             });
  123.         }
  124.     }
  125.     public override void EndWrite(IAsyncResult asyncResult)
  126.     {
  127.         if (asyncResult == null)
  128.         {
  129.             throw new ArgumentNullException(nameof(asyncResult));
  130.         }
  131.         var task = (Task)asyncResult;
  132.         task.GetAwaiter().GetResult();
  133.     }
  134.     public async Task CompleteAsync()
  135.     {
  136.         if (_complete)
  137.         {
  138.             return;
  139.         }
  140.         await FinishThrottlingAsync(); // Sets _complete
  141.         await _innerBodyFeature.CompleteAsync();
  142.     }
  143.     public void DisableBuffering()
  144.     {
  145.         _innerBodyFeature?.DisableBuffering();
  146.     }
  147.     public override void Flush()
  148.     {
  149.         if (!_throttlingChecked)
  150.         {
  151.             OnWriteAsync().ConfigureAwait(false).GetAwaiter().GetResult();
  152.             // Flush the original stream to send the headers. Flushing the compression stream won't
  153.             // flush the original stream if no data has been written yet.
  154.             _innerStream.Flush();
  155.             return;
  156.         }
  157.         if (_throttlingStream != null)
  158.         {
  159.             _throttlingStream.Flush();
  160.         }
  161.         else
  162.         {
  163.             _innerStream.Flush();
  164.         }
  165.     }
  166.     public override async Task FlushAsync(CancellationToken cancellationToken)
  167.     {
  168.         if (!_throttlingChecked)
  169.         {
  170.             await OnWriteAsync();
  171.             // Flush the original stream to send the headers. Flushing the compression stream won't
  172.             // flush the original stream if no data has been written yet.
  173.             await _innerStream.FlushAsync(cancellationToken);
  174.             return;
  175.         }
  176.         if (_throttlingStream != null)
  177.         {
  178.             await _throttlingStream.FlushAsync(cancellationToken);
  179.             return;
  180.         }
  181.         await _innerStream.FlushAsync(cancellationToken);
  182.     }
  183.     public async Task SendFileAsync(string path, long offset, long? count, CancellationToken cancellationToken)
  184.     {
  185.         await OnWriteAsync();
  186.         if (_throttlingStream != null)
  187.         {
  188.             await SendFileFallback.SendFileAsync(Stream, path, offset, count, cancellationToken);
  189.             return;
  190.         }
  191.         await _innerBodyFeature.SendFileAsync(path, offset, count, cancellationToken);
  192.     }
  193.     public async Task StartAsync(CancellationToken cancellationToken = default)
  194.     {
  195.         await OnWriteAsync();
  196.         await _innerBodyFeature.StartAsync(cancellationToken);
  197.     }
  198.     internal async Task FinishThrottlingAsync()
  199.     {
  200.         if (_complete)
  201.         {
  202.             return;
  203.         }
  204.         _complete = true;
  205.         if (_pipeAdapter != null)
  206.         {
  207.             await _pipeAdapter.CompleteAsync();
  208.         }
  209.         if (_throttlingStream != null)
  210.         {
  211.             await _throttlingStream.DisposeAsync();
  212.         }
  213.     }
  214.     private async Task OnWriteAsync()
  215.     {
  216.         if (!_throttlingChecked)
  217.         {
  218.             _throttlingChecked = true;
  219.             var maxValue = await _options.Value.ThrottlingProvider.Invoke(_httpContext);
  220.             _throttlingStream = new ThrottlingStream(_innerStream, maxValue < 0 ? 0 : maxValue);
  221.         }
  222.         if (_throttlingStream != null && _options?.Value?.ThrottlingRefreshCycle > 0)
  223.         {
  224.             if (_throttlingRefreshCycleCount >= _options.Value.ThrottlingRefreshCycle)
  225.             {
  226.                 _throttlingRefreshCycleCount = 0;
  227.                 var maxValue = await _options.Value.ThrottlingProvider.Invoke(_httpContext);
  228.                 _throttlingStream.MaximumBytesPerSecond = maxValue < 0 ? 0 : maxValue;
  229.             }
  230.             else
  231.             {
  232.                 _throttlingRefreshCycleCount++;
  233.             }
  234.         }
  235.     }
  236. }
复制代码
自定义的响应正文类必须实现IHttpResponseBodyFeature接口才能作为应用的底层响应流使用,设计和实现参考ASP.NET Core的ResponseCompressionBody。
响应限流中间件
  1. using Microsoft.AspNetCore.Http.Features;
  2. using Microsoft.Extensions.Options;
  3. using Timer = System.Timers.Timer;
  4. namespace AccessControlElementary;
  5. public class ResponseThrottlingMiddleware
  6. {
  7.     private readonly RequestDelegate _next;
  8.     public ResponseThrottlingMiddleware(RequestDelegate next)
  9.     {
  10.         _next = next;
  11.     }
  12.     public async Task Invoke(HttpContext context, IOptionsSnapshot<ResponseThrottlingOptions> options, ILogger<ResponseThrottlingMiddleware> logger)
  13.     {
  14.         ThrottlingResponseBody throttlingBody = null;
  15.         IHttpResponseBodyFeature originalBodyFeature = null;
  16.         var shouldThrottling = await options?.Value?.ShouldThrottling?.Invoke(context);
  17.         if (shouldThrottling == true)
  18.         {
  19.             //获取原始输出Body
  20.             originalBodyFeature = context.Features.Get<IHttpResponseBodyFeature>();
  21.             //初始化限流Body
  22.             throttlingBody = new ThrottlingResponseBody(originalBodyFeature, context, options);
  23.             //设置成限流Body
  24.             context.Features.Set<IHttpResponseBodyFeature>(throttlingBody);
  25.             context.Features.Set<IHttpResponseThrottlingFeature>(throttlingBody);
  26.             // 用定时器定期向外汇报信息,这可能导致性能下降,仅用于演示目的
  27.             var timer = new Timer(1000);
  28.             timer.AutoReset = true;
  29.             long? currentBitsPerSecond = null;
  30.             var traceIdentifier = context.TraceIdentifier;
  31.             timer.Elapsed += (sender, arg) =>
  32.             {
  33.                 if (throttlingBody.CurrentBitsPerSecond != currentBitsPerSecond)
  34.                 {
  35.                     currentBitsPerSecond = throttlingBody.CurrentBitsPerSecond;
  36.                     var bps = (double)(throttlingBody.CurrentBitsPerSecond ?? 0);
  37.                     var (unitBps, unit) = bps switch
  38.                     {
  39.                         < 1000 => (bps, "bps"),
  40.                         < 1000_000 => (bps / 1000, "kbps"),
  41.                         _ => (bps / 1000_000, "mbps"),
  42.                     };
  43.                     logger.LogDebug("请求:{RequestTraceIdentifier} 当前响应发送速率:{CurrentBitsPerSecond} {Unit}。", traceIdentifier, unitBps, unit);
  44.                 }
  45.             };
  46.             // 开始发送响应后启动定时器
  47.             context.Response.OnStarting(async () =>
  48.             {
  49.                 logger.LogInformation("请求:{RequestTraceIdentifier} 开始发送响应。", traceIdentifier);
  50.                 timer.Start();
  51.             });
  52.             // 响应发送完成后销毁定时器
  53.             context.Response.OnCompleted(async () =>
  54.             {
  55.                 logger.LogInformation("请求:{RequestTraceIdentifier} 响应发送完成。", traceIdentifier);
  56.                 timer.Stop();
  57.                 timer?.Dispose();
  58.             });
  59.             // 请求取消后销毁定时器
  60.             context.RequestAborted.Register(() =>
  61.             {
  62.                 logger.LogInformation("请求:{RequestTraceIdentifier} 已中止。", traceIdentifier);
  63.                 timer.Stop();
  64.                 timer?.Dispose();
  65.             });
  66.         }
  67.         try
  68.         {
  69.             await _next(context);
  70.             if (shouldThrottling == true)
  71.             {
  72.                 // 刷新响应流,确保所有数据都发送到网卡
  73.                 await throttlingBody.FinishThrottlingAsync();
  74.             }
  75.         }
  76.         finally
  77.         {
  78.             if (shouldThrottling == true)
  79.             {
  80.                 //限流发生错误,恢复原始Body
  81.                 context.Features.Set(originalBodyFeature);
  82.             }
  83.         }
  84.     }
  85. }
复制代码
中间件负责把基础响应流替换为限流响应流,并为每个请求重新读取选项,使每个请求都能够独立控制限流的速率,然后在响应发送启动后记录响应的发送速率。
响应限流选项
  1. namespace AccessControlElementary;
  2. public class ResponseThrottlingOptions
  3. {
  4.     /// <summary>
  5.     /// 获取或设置流量限制的值的刷新周期,刷新时会重新调用<see cref="ThrottlingProvider"/>设置限制值。
  6.     /// 值越大刷新间隔越久,0或负数表示永不刷新。
  7.     /// </summary>
  8.     public int ThrottlingRefreshCycle { get; set; }
  9.     /// <summary>
  10.     /// 获取或设置指示是否应该启用流量控制的委托
  11.     /// </summary>
  12.     public Func<HttpContext, Task<bool>> ShouldThrottling { get; set; }
  13.     /// <summary>
  14.     /// 获取或设置指示流量限制大小的委托(单位:Byte/s)
  15.     /// </summary>
  16.     public Func<HttpContext, Task<int>> ThrottlingProvider { get; set; }
  17. }
复制代码
响应限流服务注册和中间件配置扩展
  1. namespace AccessControlElementary;
  2. // 配置中间件用的辅助类和扩展方法
  3. public static class ResponseThrottlingMiddlewareExtensions
  4. {
  5.     public static IApplicationBuilder UseResponseThrottling(this IApplicationBuilder app)
  6.     {
  7.         return app.UseMiddleware<ResponseThrottlingMiddleware>();
  8.     }
  9. }
  10. // 注册中间件需要的服务的辅助类和扩展方法
  11. public static class ResponseThrottlingServicesExtensions
  12. {
  13.     public static IServiceCollection AddResponseThrottling(this IServiceCollection services, Action<ResponseThrottlingOptions> configureOptions = null)
  14.     {
  15.         services.Configure(configureOptions);
  16.         return services;
  17.     }
  18. }
复制代码
使用节流组件

服务注册和请求管道配置

Startup启动配置
  1. namespace AccessControlElementary;
  2. public class Startup
  3. {
  4.     public void ConfigureServices(IServiceCollection services)
  5.     {
  6.         // 注册限流服务和选项
  7.         services.AddResponseThrottling(options =>
  8.         {
  9.             options.ThrottlingRefreshCycle = 100;
  10.             options.ShouldThrottling = static async _ => true;
  11.             options.ThrottlingProvider = static async _ => 100 * 1024; // 100KB/s
  12.         });
  13.         services.AddRazorPages();
  14.     }
  15.     public void Configure(IApplicationBuilder app)
  16.     {
  17.         // 配置响应限流中间件
  18.         app.UseResponseThrottling();
  19.         app.UseStaticFiles();
  20.         app.UseRouting();
  21.         app.UseAuthentication();
  22.         app.UseAuthorization();
  23.         app.UseEndpoints(endpoints =>
  24.         {
  25.             endpoints.MapRazorPages();
  26.         });
  27.     }
  28. }
复制代码
示例展示了如何配置和启用响应限流。ThrottlingRefreshCycle设置为每100次响应流写入周期刷新一次流量限制的值,使限流值能在响应发送中动态调整;ShouldThrottling设置为无条件启用限流;ThrottlingProvider设置为限速100 KB/s。
请求只有在UseResponseThrottling之前配置的短路中间件处被处理时不会受影响,请求没有被短路的话,只要经过限流中间件,基础响应流就被替换了。如果同时使用了响应压缩,会变成限流响应包裹压缩响应(或者相反),压缩响应(或者限流响应)又包裹基础响应的嵌套结构。
结语

本书在介绍.NET 6基础知识时会尽可能使用具有现实意义的示例避免学习和实践脱节,本文就是其中之一,如果本文对您有价值,欢迎继续了解和购买本书。《C#与.NET6 开发从入门到实践》预售,作者亲自来打广告了!
本文地址:https://www.cnblogs.com/coredx/p/17195492.html

来源:https://www.cnblogs.com/coredx/archive/2023/03/08/17195492.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具