typescript - ดึงหลายคีย์ของ Redis Cache ตามรูปแบบด้วย NestJS
ปัจจุบันฉันได้สร้างแอปพลิเคชัน NestJS ที่มี Redis Cache แล้ว ฉันต้องการที่จะสามารถดึงหลายคีย์จาก Redis Cache ของฉันโดยใช้รูปแบบที่ฉันสามารถดึงคีย์ทั้งหมดที่รวมสตริงบางอย่างได้
ปัจจุบันฉันกำลังใช้ cache-manager และ cache-manager-redis-store เป็นไคลเอนต์ของฉันเพื่อให้สามารถเชื่อมต่อและเข้าถึง Redis Cache ของฉันได้ ฉันได้อ่านเอกสารแล้วเพื่อพยายามใช้ฟังก์ชัน .mget() แต่ฉันไม่สามารถหาคำตอบได้ว่าฉันสามารถส่งสตริงและดึงคีย์ทั้งหมดที่มีสตริงนั้นได้หรือไม่
ฉันกำลังคิดว่าฉันอาจจะต้องใช้ไคลเอนต์ Redis อันอื่น แต่แค่อยากดูว่ามีใครมีไอเดียอื่นไหม
คำตอบ #1
มีคุณสมบัติชื่อ store ใน cache-manager ซึ่งคุณสามารถรับคีย์ทั้งหมดโดยการเรียกใช้เมธอด keys()
นี่คือตัวอย่าง 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 + '*');คำตอบ #2
มีสองวิธีที่คุณสามารถทำสิ่งนี้ให้สำเร็จได้
เก็บชุดของกุญแจที่คุณต้องการเรียกคืนและทำ SMEMBERS อย่างไรก็ตาม คุณจะต้องดูแลชุดนี้ด้วยตนเองและเพิ่มหรือลบ
Redisearch ช่วยให้คุณสร้างดัชนีรองรอบข้อมูลสำหรับการค้นหาข้อความเต็ม ฯลฯ
