Skip to content

An AI-powered search engine with a generative UI

updated redis cache

casistacke97aa5b3d622
diff --git a/app/api/advanced-search/route.ts b/app/api/advanced-search/route.ts
index 31d87738..afa5b89e 100644
--- a/app/api/advanced-search/route.ts
+++ b/app/api/advanced-search/route.ts
@@ -23,6 +23,7 @@ const SEARXNG_MAX_RESULTS = Math.max(
)
const CACHE_TTL = 3600 // Cache time-to-live in seconds (1 hour)
+const CACHE_EXPIRATION_CHECK_INTERVAL = 3600000 // 1 hour in milliseconds
let redisClient: Redis | ReturnType<typeof createClient> | null = null
@@ -67,14 +68,20 @@ async function getCachedResults(
cachedData = await client.get(cacheKey)
}
- return cachedData ? JSON.parse(cachedData) : null
+ if (cachedData) {
+ console.log(`Cache hit for key: ${cacheKey}`)
+ return JSON.parse(cachedData)
+ } else {
+ console.log(`Cache miss for key: ${cacheKey}`)
+ return null
+ }
} catch (error) {
console.error('Redis cache error:', error)
return null
}
}
-// Function to set cached results
+// Function to set cached results with error handling and logging
async function setCachedResults(
cacheKey: string,
results: SearXNGSearchResults
@@ -89,11 +96,34 @@ async function setCachedResults(
} else {
await client.set(cacheKey, serializedResults, { EX: CACHE_TTL })
}
+ console.log(`Cached results for key: ${cacheKey}`)
} catch (error) {
console.error('Redis cache error:', error)
}
}
+// Function to periodically clean up expired cache entries
+async function cleanupExpiredCache() {
+ try {
+ const client = await initializeRedisClient()
+ if (!client) return
+
+ const keys = await client.keys('search:*')
+ for (const key of keys) {
+ const ttl = await client.ttl(key)
+ if (ttl <= 0) {
+ await client.del(key)
+ console.log(`Removed expired cache entry: ${key}`)
+ }
+ }
+ } catch (error) {
+ console.error('Cache cleanup error:', error)
+ }
+}
+
+// Set up periodic cache cleanup
+setInterval(cleanupExpiredCache, CACHE_EXPIRATION_CHECK_INTERVAL)
+
export async function POST(request: Request) {
const { query, maxResults, searchDepth, includeDomains, excludeDomains } =
await request.json()