okdewit/redis-datastructures

一个 Laravel + Redis 库,用于创建更高级的缓存数据结构

1.2.2 2024-03-27 11:31 UTC

This package is auto-updated.

Last update: 2024-08-27 12:27:07 UTC


README

一个 Laravel + Redis 库,用于创建更高级的缓存数据结构

此包已在 PHP 7.4 & PHP 8.0 下进行测试,
与 Laravel 6 及以上版本兼容,
以及与 predis/predis 包和本地的 phpredis 扩展兼容。

使用方法

此包中的当前数据结构

IndexedCache

IndexedCache 缓存对象,并可选地维护一个或多个二级索引。

$cache = new IndexedCache(

    // Name, prefix where the cached objects are stored
    'colorcache',

    // A callback used to determine where the (integer) primary key can be found on the object
    fn(Color $color) => $color->id,

    // An array with secondary index definitions.
    ['color' => fn(Color $color) => $color->color]
);

在示例中,Color 只是一个简单的 DTO 类,但它可以是任何可序列化的对象或模型。

class Color
{
    public int $id;
    public string $color;
}

可以为对象设置过期时间,以及缓存未命中时的处理程序

$cache->setTimeToLive(CarbonInterval::day())
    ->setOnMiss(fn(int $id) => new Color($id, 'purple'));

可以一次性预热缓存,也可以使用单个条目填充

$collection = new ColorCollection([
    new Color(1, 'green'),
    new Color(2, 'blue'),
    new Color(3, 'green')
]);

$cache->warm($collection);              // Flush & populate the cache
$cache->warm($collection, false);       // Do not flush, just extend the cache with missing items

$purple = new Color(4, 'purple');
$cache->put($purple); 

因为我们定义了哪些对象属性代表“主键”和(可选)“二级键”,所以我们可以有效地从缓存中检索项目

// Find by primary index (unique),
// O(1)
$color = $cache->find(4);
$this->assertEquals($purple, $color);

// Find by secondary index (non unique, collection),
// O(log(N)+M), equal time complexity to an SQL BTREE index.
$colorCollection = $cache->findBy('color', $color);
$this->assertEquals(2, $colorCollection->count());

// Group by secondary index
$colorCollection = $cache->groupBy('color');
$this->assertEquals(['blue', 'green', 'purple'], $colorCollection->keys());

findBy 返回一个包含所有匹配索引约束的对象的普通 Illuminate\Support\Collection
当然,可以使用类似 ->pipeInto(ColorCollection::class) 的方式将其转换为自定义集合。

groupBy 返回一个包含多个 CollectionsLazyCollection,所有对象按提供的二级索引分组。

最后,也可以检索整个缓存或清空它

$colorCollection = $cache->all();
$cache->flush();

测试

运行 composer update,然后 composer test

默认情况下,它将使用 predis 客户端,并假定连接详细信息如 phpunit.xml.dist 中定义。在运行测试之前,可以通过复制并编辑 dist 文件到 phpunit.xml 来自定义。

在 Github Actions 上,该包将针对 predis 和 phpredis 进行测试。