// src/main/redis/keys.ts // Key 操作 import { getClient } from './connection' export async function getKeyType(id: string, key: string): Promise { const client = getClient(id) if (!client) throw new Error(`Client ${id} not found`) return client.type(key) } export async function getKeyTTL(id: string, key: string): Promise { const client = getClient(id) if (!client) throw new Error(`Client ${id} not found`) return client.ttl(key) } export async function deleteKey(id: string, key: string): Promise { const client = getClient(id) if (!client) throw new Error(`Client ${id} not found`) await client.del(key) } export async function setKeyTTL(id: string, key: string, ttl: number): Promise { const client = getClient(id) if (!client) throw new Error(`Client ${id} not found`) if (ttl < 0) { await client.persist(key) } else { await client.expire(key, ttl) } } export async function renameKey(id: string, oldKey: string, newKey: string): Promise { const client = getClient(id) if (!client) throw new Error(`Client ${id} not found`) await client.rename(oldKey, newKey) } export async function existsKey(id: string, key: string): Promise { const client = getClient(id) if (!client) throw new Error(`Client ${id} not found`) return (await client.exists(key)) === 1 } export async function batchDelete(id: string, keys: string[]): Promise { const client = getClient(id) if (!client) throw new Error(`Client ${id} not found`) if (keys.length === 0) return 0 const pipeline = client.pipeline() for (const key of keys) { pipeline.del(key) } const results = await pipeline.exec() return results?.filter(([err]) => !err).length ?? 0 } export async function memoryUsage(id: string, key: string): Promise { const client = getClient(id) if (!client) throw new Error(`Client ${id} not found`) return client.memory('USAGE', key) as Promise } export async function scanKeys( id: string, cursor: string, pattern: string, count: number ): Promise<{ cursor: string; keys: string[] }> { const client = getClient(id) if (!client) throw new Error(`Client ${id} not found`) const [nextCursor, keys] = await client.scan(cursor, 'MATCH', pattern, 'COUNT', count) return { cursor: nextCursor, keys } }