Deleting Items and Flushing our Redis Cache

Not everyone is perfect, and one day you'll accidentally cache bad data and need a way to quickly clear it out. In this lesson, we'll learn how we can create two routes to clear a single Redis key or flush the entire database.

Published
Feb 04, 24
Duration
6m 46s

Developer, dog lover, and burrito eater. Currently teaching AdonisJS, a fully featured NodeJS framework, and running Adocasts where I post new lessons weekly. Professionally, I work with JavaScript, .Net C#, and SQL Server.

Adocasts

Burlington, KY

Get the Code

Download or explore the source code for this lesson on GitHub

Repository

Join The Discussion! (4 Comments)

Please sign in or sign up for free to join in on the dicussion.

  1. Commented 7 days ago

    After testing with these two route methods, there were no changes in the Redis database. The three movie records still remain—they haven't been destroyed or deleted.

    //routes.ts
    router.get('/redis/flush', [RedisController, 'flush']).as('redis.flush')
    router.get('/redis/:slug', [RedisController, 'destroy']).as('redis.destroy')
    Copied!

    1

    Please sign in or sign up for free to reply

    1. Commented 7 days ago
      //redis controller
      export default class RedisController {
          public async destroy({ response, params }: HttpContext) {
              await cache.delete(params.slug)
              return response.redirect().back()
          }
      
          public async flush({ response }: HttpContext) {
              await cache.flushDb()
              return response.redirect().back()
          }
      }
      Copied!
      1

      Please sign in or sign up for free to reply

    2. Commented 7 days ago
      //cache service
      export class CacheService {
        async has(...keys: string[]) {
          return redis.exists(keys)
        }
        async get(key: string) {
          const value = await redis.get(key)
          return value && JSON.parse(value)
        }
        async set(key: string, value: any) {
          return redis.set(key, JSON.stringify(value))
        }
        async delete(...keys: string[]) {
          return redis.del(keys)
        }
        async flushDb() {
          return redis.flushdb()
        }
      }
      const cache = new CacheService()
      export default cache
      Copied!
      1

      Please sign in or sign up for free to reply

    3. Commented 6 days ago

      Hi codthing! Everything you've shared looks right. If you're viewing your Redis database with a GUI application, those often don't reflect live data and require refreshing in order for them to reflect changes made to the database contents. Also, make sure you're viewing the Redis database actually being used by your application! This can be found within config/redis.ts

      
      const redisConfig = defineConfig({
        connection: 'main',
      
        connections: {
          main: {
            host: env.get('REDIS_HOST'),
            port: env.get('REDIS_PORT'),
            password: env.get('REDIS_PASSWORD', ''),
            db: 1, // 👈 indicates I'm using Redis DB1, DB0 is typically the default
            keyPrefix: '',
            retryStrategy(times) {
              return times > 10 ? null : times * 50
            },
          },
        },
      })
      Copied!
      • config
      • redis.ts

      You might also do a sanity check, just to ensure your controller methods are actually being hit correctly, by adding a console log to each.

      //redis controller
      export default class RedisController {
          public async destroy({ response, params }: HttpContext) {
              console.log('destroy', params.slug)
              await cache.delete(params.slug)
              return response.redirect().back()
          }
      
          public async flush({ response }: HttpContext) {
              console.log('flushing redis')
              await cache.flushDb()
              return response.redirect().back()
          }
      }
      Copied!

      If neither of those help, please feel free to share a link to your repository and I can take a deeper look to see if anything stands out!

      0

      Please sign in or sign up for free to reply