使用 NestJS 基于模式获取多个 Redis 缓存键

2023-12-26

目前我已经创建了一个带有 Redis 缓存的 NestJS 应用程序。我希望能够通过使用一种模式从 Redis 缓存中获取多个键,在该模式中我可以获得包含某个字符串的所有键。

目前我正在使用缓存管理器 and 缓存管理器 redis 存储作为我的客户端能够连接和访问我的 Redis 缓存。我已经阅读了文档来尝试使用 .mget() 函数,但我无法弄清楚是否可以以某种方式传递字符串并获取包含该字符串的所有键。

我想我可能不得不使用不同的 Redis 客户端,但只是想看看是否有人有其他想法。


有一个属性名为store in cache-manager您可以通过调用从中获取所有密钥keys() method.

这是示例 redisService

import { Injectable, Inject, CACHE_MANAGER } from '@nestjs/common';
import { Cache } from 'cache-manager';

@Injectable()
export class RedisCacheService {
    constructor(@Inject(CACHE_MANAGER) private readonly cache: Cache) {}

    async getKeys(key: string): Promise<any> {
        return await this.cache.store.keys(key);
    }

    async getValue(key: string): Promise<string> {
        return await this.cache.get(key);
    }

    async save(key: string, value: any, ttl: number): Promise<any> {
        return await this.cache.set(key, value, {
            ttl: ttl,
        });
    }

    async delete(key: string): Promise<void> {
        return await this.cache.del(key);
    }

    async getMultipleKeydata(key: string): Promise<any> {
        const redisKeys = await this.getKeys(key);
        const data: { [key: string]: any } = {};
        for (const key of redisKeys) {
            data[key] = await this.getValue(key);
        }
        return allData;
    }
}

然后你可以使用这个服务来获取多个键或者可以获取多个键的值

await this.redisService.getKeys('*' + email + '*');

您还可以获取多个键的值

await this.redisService.getMultipleKeydata('*' + email + '*');

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 NestJS 基于模式获取多个 Redis 缓存键 的相关文章

随机推荐