|
| 1 | +import Redis from "ioredis"; |
| 2 | +import { IDatabaseCacheAdapter, UUID, elizaLogger } from "@ai16z/eliza"; |
| 3 | + |
| 4 | +export class RedisClient implements IDatabaseCacheAdapter { |
| 5 | + private client: Redis; |
| 6 | + |
| 7 | + constructor(redisUrl: string) { |
| 8 | + this.client = new Redis(redisUrl); |
| 9 | + |
| 10 | + this.client.on("connect", () => { |
| 11 | + elizaLogger.success("Connected to Redis"); |
| 12 | + }); |
| 13 | + |
| 14 | + this.client.on("error", (err) => { |
| 15 | + elizaLogger.error("Redis error:", err); |
| 16 | + }); |
| 17 | + } |
| 18 | + |
| 19 | + async getCache(params: { |
| 20 | + agentId: UUID; |
| 21 | + key: string; |
| 22 | + }): Promise<string | undefined> { |
| 23 | + try { |
| 24 | + const redisKey = this.buildKey(params.agentId, params.key); |
| 25 | + const value = await this.client.get(redisKey); |
| 26 | + return value || undefined; |
| 27 | + } catch (err) { |
| 28 | + elizaLogger.error("Error getting cache:", err); |
| 29 | + return undefined; |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + async setCache(params: { |
| 34 | + agentId: UUID; |
| 35 | + key: string; |
| 36 | + value: string; |
| 37 | + }): Promise<boolean> { |
| 38 | + try { |
| 39 | + const redisKey = this.buildKey(params.agentId, params.key); |
| 40 | + await this.client.set(redisKey, params.value); |
| 41 | + return true; |
| 42 | + } catch (err) { |
| 43 | + elizaLogger.error("Error setting cache:", err); |
| 44 | + return false; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + async deleteCache(params: { |
| 49 | + agentId: UUID; |
| 50 | + key: string; |
| 51 | + }): Promise<boolean> { |
| 52 | + try { |
| 53 | + const redisKey = this.buildKey(params.agentId, params.key); |
| 54 | + const result = await this.client.del(redisKey); |
| 55 | + return result > 0; |
| 56 | + } catch (err) { |
| 57 | + elizaLogger.error("Error deleting cache:", err); |
| 58 | + return false; |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + async disconnect(): Promise<void> { |
| 63 | + try { |
| 64 | + await this.client.quit(); |
| 65 | + elizaLogger.success("Disconnected from Redis"); |
| 66 | + } catch (err) { |
| 67 | + elizaLogger.error("Error disconnecting from Redis:", err); |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + private buildKey(agentId: UUID, key: string): string { |
| 72 | + return `${agentId}:${key}`; // Constructs a unique key based on agentId and key |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +export default RedisClient; |
0 commit comments