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

标签 typescript redis nestjs

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

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

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

最佳答案

有名为 store 的属性在cache-manager您可以通过调用 keys() 获取所有 key 方法。

这是示例 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 + '*');

关于typescript - 使用 NestJS 基于模式获取多个 Redis 缓存键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69156422/

相关文章:

javascript - 我正在尝试制作响应式文本,但无论屏幕有多大,它的大小都是固定的

typescript - Typescript 版本是否向后兼容?

浏览器中缺少 Angular 12 源映射

redis - 脚本 flushall - 怎么样?

c# - 使用 ServiceStack.Redis 对高容量场景的意外回复

typescript - Nest.js 无法解析依赖项

mongodb - ParseObjectIdPipe 获取 MongoDB 的 ObjectID

templates - Angular2 表达式不呈现

python - 使用 Python 将保存的 `graphdata` 加载回 redisgraph 实例时出现问题

node.js - 多对多关系的正确文件夹结构