aponscat/timeseries-set

在集合中添加标签,然后检索给定时间内的标签数量

安装: 14

依赖: 0

建议: 0

安全: 0

星标: 0

关注者: 1

分支: 0

开放问题: 0

类型:

v1.0.3 2022-10-23 14:58 UTC

This package is auto-updated.

Last update: 2024-09-23 18:58:27 UTC


README

此包允许您在不同时间添加不同的“标签”,集合“统计”给定时间段内出现的“标签”数量。

默认时间段为“一分钟”('YmdHi')。您可以通过对象构造函数的第二个参数更改此行为。例如,使用值 'YmdH' 创建“一小时”的时间段计数器。

用法

use Apons\TimeSeriesSet\TimeSeriesSet;
use Apons\TimeSeriesSet\Adapters\Memcached\MemcachedSet;
use Apons\TimeSeriesSet\Adapters\Memcached\MemcachedSetStorage;
use Apons\TimeSeriesSet\Interfaces\SetStorageInterface;
...

// Create a new memcached object
$m = new \Memcached();
$m->addServer('localhost', 11211);
$m->setOption(\Memcached::OPT_COMPRESSION, false);

// Create a MemcachedSetStorage object injecting the memcached connection
// The second parameter indicates the number of seconds that memcached 
// will keep the items stored (default 3.600 seconds (1 hour))
$s=new MemcachedSetStorage($m, 3600);

// Create a new TimeSeriesSet injecting the MemcachedSet newly created
// note than the second parameter sets the time frame used
// For example:
// 'YmdHi' --> minute intervals
// 'YmdH'  --> hour interval
$timeSeriesSet=new TimeSeriesSet(new MemcachedSet($s), 'YmdHi');

// Add the tag you want to count, by default counts this tag in the current time()
// use the second optional parameter to pass a timestamp (used for testing purposes usually)
$timeSeriesSet->add('tag1999');

or 

$timeSeriesSet->add('tag1999', (new DateTime("2022-02-02 10:01:02"))->getTimestamp());
...

// Finally count the tags in a given time period
$set=$timeSeriesSet->getAllTagsInTime((new DateTime("2022-02-02 10:00"))->getTimestamp());

// Returns an array of tags with is count
// For example, if we add tag1999 in the given time ("2022-02-02 10:00")
// The result will be ['tag1999'=>1]

当然,添加和计数(getAllTagsInTime)可以在不同的进程和执行中。

一个典型用例是速率限制器。

在速率限制器中,对给定URL的每个请求都可以通过标签添加到TimeSeriesSet中。之后,cron作业可以计数在时间段内所有给定标签的请求,并决定是否达到限制。

要计数的示例请求:/sample-url/27773 (2022-02-02 10:00:03) /sample-url/27773 (2022-02-02 10:00:08) /sample-url/27773 (2022-02-02 10:00:11) /sample-url/27773 (2022-02-02 10:00:12) /sample-url/27773 (2022-02-02 10:00:25) /sample-url/27773 (2022-02-02 10:00:59)

/sample-url/19999 (2022-02-02 10:00:05) /sample-url/19999 (2022-02-02 10:00:12) /sample-url/19999 (2022-02-02 10:00:33) /sample-url/19999 (2022-02-02 10:00:55)

然后在计数时间段内所有请求的cronjob(2022-02-02 10:00 至 2022-02-02 10:59)中,结果将是

[
    '27773'=>6,
    '19999'=>4
]

测试

使用以下方式测试包

./vendor/bin/phpunit tests