Skip to content

if redis connection fails, fall back to memory cache #215

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 12 additions & 13 deletions src/apicache.js
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ function ApiCache() {
debug('clearing cached entry for "' + key + '"')
clearTimeout(timers[key])
delete timers[key]
if (!globalOptions.redisClient) {
if (!(redis && redis.connected)) {
memCache.delete(key)
} else {
try {
Expand All @@ -322,7 +322,7 @@ function ApiCache() {
clearTimeout(timers[target])
delete timers[target]
// clear actual cached entry
if (!redis) {
if (!(redis && redis.connected)) {
memCache.delete(target)
} else {
try {
Expand All @@ -347,7 +347,7 @@ function ApiCache() {
} else {
debug('clearing entire index')

if (!redis) {
if (!(redis && redis.connected)) {
memCache.clear()
} else {
// clear redis keys one by one from internal index to prevent clearing non-apicache entries
Expand Down Expand Up @@ -632,16 +632,6 @@ function ApiCache() {

// attempt cache hit
var redis = opt.redisClient
var cached = !redis ? memCache.getValue(key) : null

// send if cache hit from memory-cache
if (cached) {
var elapsed = new Date() - req.apicacheTimer
debug('sending cached (memory-cache) version of', key, logDuration(elapsed))

perf.hit(key)
return sendCachedResponse(req, res, cached, middlewareToggle, next, duration)
}

// send if cache hit from redis
if (redis && redis.connected) {
Expand Down Expand Up @@ -679,6 +669,15 @@ function ApiCache() {
return makeResponseCacheable(req, res, next, key, duration, strDuration, middlewareToggle)
}
} else {
// fallback to memory cache for redis not connected or no redis given
var cached = memCache.getValue(key) || null
if (cached) {
var elapsed = new Date() - req.apicacheTimer
debug('sending cached (memory-cache) version of', key, logDuration(elapsed))
perf.hit(key)
return sendCachedResponse(req, res, cached, middlewareToggle, next, duration)
}

perf.miss(key)
return makeResponseCacheable(req, res, next, key, duration, strDuration, middlewareToggle)
}
Expand Down