dorantor/mcounter

一个简单的基于memcached的计数器库。

v1.3.0 2021-07-29 15:40 UTC

This package is auto-updated.

Last update: 2024-09-29 04:14:35 UTC


README

非常简单的基于memcached的计数器。

安装

composer require dorantor/mcounter

用法

注意!这里只提供抽象类,因为它旨在被扩展。

class MyCounter extends \Dorantor\AbstractCounter
{
    /**
     * Method for building cache key based on $item value
     *
     * @return string
     */
    protected function getKey()
    {
        return 'myCounter' . (int) $this->item->id;
    }
}

在你的代码中

$client = new Memcached();
// .. client setup
// 
// basically, $client creation is up to you.
// Most probably you already created one earlier, so just reuse it here.
$counter = new MyCounter($user, $client);
if ($counter->value() < 100) {
    $counter->inc();
}

默认设置为永不过期。但如果你需要使用自动过期的计数器(标记?),你可以在构造函数中设置第三个参数

$counter = new MyCounter($user, $client, 3600); // hour, in this case

或者你可以在计数器内部定义过期逻辑/值,通过重写 getExpiry() 方法,例如:

protected function getExpiry()
{
    return 3600; // also hour, but this way it's defined inside counter
    // or it could be some logic based on value(s) in $this->item
}

注意! 在inc()调用时不会更新过期时间。这是Memcached的默认行为。如果你需要更新过期时间,请使用 touch(),例如:

$counter->inc();
$counter->touch();
// or
$counter->incWithTouch();

第二种方法更方便,但你将失去对 touch() 成功/失败的控制。

如果你需要重置计数器,你有两种选择

// this will delete counter, so it will be recreated
$counter->delete();

// this will get data from getInitialData() method
// and put it as current counter value
$counter->reload();

delete() 更适合用于缓存重置的情况,reload() - 当你需要将计数器与系统中的当前值同步时,例如,如果你的计数器值是 select count(*) from tablename

重要提示。 你必须在memcached中使用二进制协议。例如,可以这样启用:

$client->setOption(\Memcached::OPT_SERIALIZER, \Memcached::SERIALIZER_IGBINARY);
$client->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);

但你也需要一个安装了二进制序列化程序,就像你看到的。例如,我使用的是Igbinary。