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