欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.Net Core限流的实现示例

程序员文章站 2022-05-03 12:05:56
一、环境1.vs20192..net core 3.13.引用 aspnetcoreratelimit 4.0.1二、基础使用1.设置在startup文件中配置如下,把配置项都放在前面:2.规则设置规...

一、环境

1.vs2019

2..net core 3.1

3.引用 aspnetcoreratelimit 4.0.1

二、基础使用

1.设置

在startup文件中配置如下,把配置项都放在前面:

 public void configureservices(iservicecollection services)
 {
  // 从appsettings.json中加载ip限流配置通用规则
  services.configure<ipratelimitoptions>(configuration.getsection("ipratelimiting"));
  // 从appsettings.json中加载ip限流规则
  services.configure<ipratelimitpolicies>(configuration.getsection("ipratelimiting:ipratelimitpolicies"));
  // 从appsettings.json中加载客户端限流配置通用规则
  services.configure<clientratelimitoptions>(configuration.getsection("ipratelimiting"));
  // 从appsettings.json中加载客户端限流规则
  services.configure<clientratelimitpolicies>(configuration.getsection("ipratelimiting:clientratelimitpolicies"));
  // 注入计数器和规则存储
  services.addinmemoryratelimiting();
  // 配置(解析器、计数器密钥生成器)
  services.addsingleton<iratelimitconfiguration, ratelimitconfiguration>();
  //解析clientid和ip的使用有用,如果默认没有启用,则此处启用
  //services.addsingleton<ihttpcontextaccessor, httpcontextaccessor>();
}
public void configure(iapplicationbuilder app, ihostingenvironment env)
{
  //调用ip限流方式和客户端限流方式
  //只能选用一个,后一个调用的生效,也就是说ip规则限流和客户端限流的特殊规则不能同时使用,但是通用规则不影响
  app.useipratelimiting();
  app.useclientratelimiting();
}

2.规则设置

规则的设置分为两个大类:通过ip限流和通过客户端限流。都通过配置文件来配置参数,在appsettings.json中配置如下(也可以另起配置文件):

"ipratelimiting": {
    "enableendpointratelimiting": false,
    "stackblockedrequests": false,
    "realipheader": "x-real-ip",
    "clientidheader": "x-clientid",
    "httpstatuscode": 429,
    //"ipwhitelist": [ "198.0.0.1", "::1/10", "192.168.0.13/24" ],
    "endpointwhitelist": [ "get:/api/license", "*:/api/status" ],
    "clientwhitelist": [ "dev-id-1", "dev-id-2" ],
    "quotaexceededresponse": {
      "content": "{{\"code\":429,\"msg\":\"visit too frequently, please try again later\",\"data\":null}}",
      "contenttype": "application/json;utf-8",
      "statuscode": 429
    },
    "generalrules": [
      {
        "endpoint": "*",
        "period": "1s",
        "limit": 2
      }
    ],
    "clientratelimitpolicies": {
      "clientrules": [
        {
          "clientid": "client-id-1",
          "rules": [
            {
              "endpoint": "*",
              "period": "1s",
              "limit": 10
            },
            {
              "endpoint": "*",
              "period": "15m",
              "limit": 200
            }
          ]
        }
      ]
    },
    "ipratelimitpolicies": {
      "iprules": [
        {
          "ip": "84.247.85.224",
          "rules": [
            {
              "endpoint": "*",
              "period": "1s",
              "limit": 10
            },
            {
              "endpoint": "*",
              "period": "15m",
              "limit": 200
            }
          ]
        }
      ]
    }
  }

各配置项的说明如下:

 enableendpointratelimiting:设置为true,则端点规则为 * 的时候所有的谓词如get、post等分别享有限制次数。例如,如果您为*:/api/values客户端设置每秒get /api/values5 次调用的限制,则每秒可以调用5 次,但也可以调用5 次put /api/values。

如果设置为false,则上述例子中get、post等请求共享次数限制。是否共享限制次数的设置。这里有个注意的地方,就是当该参数设置为false的时候,只有端点设置为星号*的规则有效,其他规则无效,设置为true时所有规则有效。

stackblockedrequests:设为false的情况下,被拒绝的请求不会加入到计数器中,如一秒内有三个请求,限流规则分别为一秒一次和一分钟三次,则被拒绝的两个请求是不会记录在一分钟三次的规则中的,也就是说这一分钟还能调用两次该接口。设置为true的话,则被拒绝的请求也会加入计数器,像上述例子中的情况,一分钟内就不能调用了,三次全部记录了。

realipheader:与配置项ip白名单ipwhitelist组合使用,如果该参数定义的请求头名称存在于一个请求中,并且该参数内容为ip白名单中的ip,则不受限流规则限制。

clientidheader:与配置项客户端白名单clientidheader组合使用,如果该参数定义的请求头名称存在于一个请求中,并且该参数内容为客户端白名单中的名称,则不受限流规则限制。

httpstatuscode:http请求限流后的返回码。

ipwhitelist:ip白名单,字段支持支持ip v4和v6如 "198.0.0.1", "::1/10", "192.168.0.13/24"等。可以配合realipheader参数使用,也单独使用,请求的ip符合该白名单规则任意一条,则不受限流规则限制。

endpointwhitelist:终端白名单,符合该终端规则的请求都将不受限流规则影响,如"get:/api/values"表示get请求的api/values接口不受影响,*表示所有类型的请求。

clientwhitelist:客户端白名单,配合clientidheader参数使用,配置客户端的名称。

quotaexceededresponse:限流后的返回值设置,返回内容、状态码等。

generalrules:通用规则设置,有三个参数为endpoint、period和limit。

endpoint端点格式为{http_verb}:{path},可以使用星号来定位任何 http 动词,如get:/api/values。

period期间格式为{int}{period_type},可以使用以下期间类型之一:s、m、h、d,分别为秒分时天。

limit限制格式为{long},访问次数。

clientratelimitpolicies:客户端限流的特殊配置,规则和通用规则一样设置,只不过需要配合clientidheader在请求头中来使用,需要使用app.useclientratelimiting();启用,否则无效。这个参数名称是可以更改的噢。通用规则和特殊规则是同优先级的。

ipratelimitpolicies:ip限流的特殊配置,规则和通用规则一样设置,只不过需要配合realipheader在请求头中来使用,需要使用app.useipratelimiting();启用,否则无效。这个参数名称是可以更改的噢。通用规则和特殊规则是同优先级的。

3.特殊规则的启用

ip和客户端特殊规则的启用需要改造program文件中的程序入口如下,分别发送各自的特殊规则:

public static async task main(string[] args)
{
  iwebhost webhost = createwebhostbuilder(args).build();
  using (var scope = webhost.services.createscope())
  {
    var clientpolicystore = scope.serviceprovider.getrequiredservice<iclientpolicystore>();
    await clientpolicystore.seedasync();

    var ippolicystore = scope.serviceprovider.getrequiredservice<iippolicystore>();
    await ippolicystore.seedasync();
  }
  await webhost.runasync();
}  

在configureservices中读取配置参数,之后是在startup文件中的configure方法选择app.useipratelimiting()或app.useclientratelimiting()启动ip特殊规则或者客户端特殊规则,都存在的情况下,先执行的先生效。

 三、请求返回头

限流启动后,执行限流规则的返回头会有三个参数分别为:

x-rate-limit-limit:现在时间,如1d。

x-rate-limit-remaining:剩余可请求次数。

x-rate-limit-reset:下次请求次数重置时间。

多个限制规则会采用最长的周期的规则显示。

在配置文件中配置返回信息,除了返回提示信息外,还可以返回限制规则提醒,如下

"content": "{{\"code\":429,\"msg\":\"访问太频繁了,每{1}{0}次,请在{2}秒后重试\",\"data\":null}}",

{0}可以替换当前阻止规则规定的次数,{1}可以替换时间区间带单位s、h等,{2}替换几秒后尝试当单位为天或者小时等都会换算成秒。

四、使用redis存储

限流规则等目前都是通过内存存储的,我们结合实际会使用redis存储。使用microsoft.extensions.caching.redis可以达到这么目的。

但是好像会存在性能问题,所以我们自己替换,使用的是用csredis封装的方法,不过这里不做阐述。

我们缓存三类数据1、访问计数2、ip特殊规则3、客户端特殊规则

1、访问计数

public class redisratelimitcounterstore : iratelimitcounterstore
    {
        private readonly ilogger _logger;
        private readonly iratelimitcounterstore _memorycachestore;
        private readonly rediscache _rediscache;

        public redisratelimitcounterstore(
            imemorycache memorycache,
            ilogger<redisratelimitcounterstore> logger)
        {
            _logger = logger;
            _memorycachestore = new memorycacheratelimitcounterstore(memorycache);

            _rediscache = new rediscache();
        }

        public async task<bool> existsasync(string id, cancellationtoken cancellationtoken = default)
        {
            cancellationtoken.throwifcancellationrequested();

            return await tryrediscommandasync(
                () =>
                {
                    return _rediscache.keyexistsasync(id, 0);
                },
                () =>
                {
                    return _memorycachestore.existsasync(id, cancellationtoken);
                });
        }

        public async task<ratelimitcounter?> getasync(string id, cancellationtoken cancellationtoken = default)
        {
            cancellationtoken.throwifcancellationrequested();

            return await tryrediscommandasync(
                async () =>
                {
                    var value = await _rediscache.getstringasync(id, 0);

                    if (!string.isnullorempty(value))
                    {
                        return jsonconvert.deserializeobject<ratelimitcounter?>(value);
                    }

                    return null;
                },
                () =>
                {
                    return _memorycachestore.getasync(id, cancellationtoken);
                });
        }

        public async task removeasync(string id, cancellationtoken cancellationtoken = default)
        {
            cancellationtoken.throwifcancellationrequested();

            _ = await tryrediscommandasync(
                async () =>
                {
                    await _rediscache.keydeleteasync(id, 0);

                    return true;
                },
                async () =>
                {
                    await _memorycachestore.removeasync(id, cancellationtoken);

                    return true;
                });
        }

        public async task setasync(string id, ratelimitcounter? entry, timespan? expirationtime = null, cancellationtoken cancellationtoken = default)
        {
            cancellationtoken.throwifcancellationrequested();

            _ = await tryrediscommandasync(
                async () =>
                {
                    var exprie = expirationtime.hasvalue ? convert.toint32(expirationtime.value.totalseconds) : -1;
                    await _rediscache.setstringasync(id, jsonconvert.serializeobject(entry.value), exprie);

                    return true;
                },
                async () =>
                {
                    await _memorycachestore.setasync(id, entry, expirationtime, cancellationtoken);

                    return true;
                });
        }

        private async task<t> tryrediscommandasync<t>(func<task<t>> command, func<task<t>> fallbackcommand)
        {
            if (_rediscache != null)
            {
                try
                {
                    return await command();
                }
                catch (exception ex)
                {
                    _logger.logerror($"redis command failed: {ex}");
                }
            }

            return await fallbackcommand();
        }
    }

 2、ip特殊规则

public class redisippolicystore : iippolicystore
    {
        private readonly ipratelimitoptions _options;
        private readonly ipratelimitpolicies _policies;
        private readonly rediscache _rediscache;
        public redisippolicystore(
            ioptions<ipratelimitoptions> options = null,
            ioptions<ipratelimitpolicies> policies = null)
        {
            _options = options?.value;
            _policies = policies?.value;
            _rediscache = new rediscache();
        }

        public async task<bool> existsasync(string id, cancellationtoken cancellationtoken = default)
        {
            return await _rediscache.keyexistsasync($"{_options.ippolicyprefix}", 0);
        }

        public async task<ipratelimitpolicies> getasync(string id, cancellationtoken cancellationtoken = default)
        {
            string stored = await _rediscache.getstringasync($"{_options.ippolicyprefix}", 0);
            if (!string.isnullorempty(stored))
            {
                return jsonconvert.deserializeobject<ipratelimitpolicies>(stored);
            }

            return default;
        }

        public async task removeasync(string id, cancellationtoken cancellationtoken = default)
        {
            await _rediscache.delstringasync($"{_options.ippolicyprefix}", 0);
        }

        public async task seedasync()
        {
            // on startup, save the ip rules defined in appsettings
            if (_options != null && _policies != null)
            {
                await _rediscache.setstringasync($"{_options.ippolicyprefix}", jsonconvert.serializeobject(_policies), 0).configureawait(false);
            }
        }

        public async task setasync(string id, ipratelimitpolicies entry, timespan? expirationtime = null, cancellationtoken cancellationtoken = default)
        {
            var exprie = expirationtime.hasvalue ? convert.toint32(expirationtime.value.totalseconds) : -1;
            await _rediscache.setstringasync($"{_options.ippolicyprefix}", jsonconvert.serializeobject(_policies), 0, exprie);
        }
    }

3、客户端特殊规则

public class redisclientpolicystore : iclientpolicystore
    {
        private readonly clientratelimitoptions _options;
        private readonly clientratelimitpolicies _policies;
        private readonly rediscache _rediscache;
        public redisclientpolicystore(
            ioptions<clientratelimitoptions> options = null,
            ioptions<clientratelimitpolicies> policies = null)
        {
            _options = options?.value;
            _policies = policies?.value;
            _rediscache = new rediscache();
        }

        public async task<bool> existsasync(string id, cancellationtoken cancellationtoken = default)
        {
            return await _rediscache.keyexistsasync($"{_options.clientpolicyprefix}", 0);
        }

        public async task<clientratelimitpolicy> getasync(string id, cancellationtoken cancellationtoken = default)
        {
            string stored = await _rediscache.getstringasync($"{_options.clientpolicyprefix}", 0);
            if (!string.isnullorempty(stored))
            {
                return jsonconvert.deserializeobject<clientratelimitpolicy>(stored);
            }

            return default;
        }

        public async task removeasync(string id, cancellationtoken cancellationtoken = default)
        {
            await _rediscache.delstringasync($"{_options.clientpolicyprefix}", 0);
        }

        public async task seedasync()
        {
            // on startup, save the ip rules defined in appsettings
            if (_options != null && _policies != null)
            {
                await _rediscache.setstringasync($"{_options.clientpolicyprefix}", jsonconvert.serializeobject(_policies), 0).configureawait(false);
            }
        }

        public async task setasync(string id, clientratelimitpolicy entry, timespan? expirationtime = null, cancellationtoken cancellationtoken = default)
        {
            var exprie = expirationtime.hasvalue ? convert.toint32(expirationtime.value.totalseconds) : -1;
            await _rediscache.setstringasync($"{_options.clientpolicyprefix}", jsonconvert.serializeobject(_policies), 0, exprie);
        }
    }

之后在startup文件中增加对应的注入

services.addsingleton<iratelimitcounterstore, redisratelimitcounterstore>();
services.addsingleton<iippolicystore, redisippolicystore>();
services.addsingleton<iclientpolicystore, redisclientpolicystore>();


之后运行就可以在redis中看到啦

.Net Core限流的实现示例

 五、修改规则

规则只能修改ip和客户端的特殊规则,因为上一部分已经注入了改规则的对应redis增删查改的功能,所以我们可以利用这些方法重写规则,如下:

public class clientratelimitcontroller : controller
{
    private readonly clientratelimitoptions _options;
    private readonly iclientpolicystore _clientpolicystore;

    public clientratelimitcontroller(ioptions<clientratelimitoptions> optionsaccessor, iclientpolicystore clientpolicystore)
    {
        _options = optionsaccessor.value;
        _clientpolicystore = clientpolicystore;
    }

    [httpget]
    public clientratelimitpolicy get()
    {
        return _clientpolicystore.get($"{_options.clientpolicyprefix}_cl-key-1");
    }

    [httppost]
    public void post()
    {
        var id = $"{_options.clientpolicyprefix}_cl-key-1";
        var clpolicy = _clientpolicystore.get(id);
        clpolicy.rules.add(new ratelimitrule
        {
            endpoint = "*/api/testpolicyupdate",
            period = "1h",
            limit = 100
        });
        _clientpolicystore.set(id, clpolicy);
    }
}

到此这篇关于.net core限流的实现示例的文章就介绍到这了,更多相关.net core限流内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: .Net Core 限流