sequelize-redis-cache icon indicating copy to clipboard operation
sequelize-redis-cache copied to clipboard

How to clear cache?

Open btimeteam opened this issue 8 years ago • 4 comments

I have a problem that when I update a model the cache does not update, the same information remains, I tried to hook them in sequelize, but it did not work.

const   config      = require('../config'),
        Sequelize   = require('sequelize'),
        cacher      = require('sequelize-redis-cache'),
        redis       = require('redis'),
        redisCache  = redis.createClient(config.redis.port, config.redis.host),
        database    = new Sequelize(config.DATABASE_URI, {
            define: {
                hooks: {
                    afterCreate:    (instance, options) => clearCache(instance, options),
                    afterDestroy:   (instance, options) => clearCache(instance, options),
                    afterUpdate:    (instance, options) => clearCache(instance, options),
                    afterSave:      (instance, options) => clearCache(instance, options),
                    afterUpsert:    (instance, options) => clearCache(instance, options),
                }
            }
        });

const clearCache = function(instance, options) {
    if (instance.constructor.name === 'Session') {
        return;
    }

    cacher(database, redisCache).model(instance.constructor.name).clearCache();
};

btimeteam avatar Oct 05 '17 19:10 btimeteam

Hey thanks for pointing this out! Is there any chance you can give me a reproducible test case? Maybe an example with models, an instance, etc? That would help me chase this down.

rfink avatar Oct 06 '17 12:10 rfink

I am about to just write a custom solution for my platform. It seems like every one will have special cases. If I come up with general use code, I'll share and do a pull request. I am going to hook onto the Sequelize hooks beforeUpdate, afterUpdate, etc. and just read from the cache! Always store the update to the database as well for persistent storage. Now, when the app restarts, I want to go a step further and load items into Redis cache RAM for fast data access.

knoxcard avatar Jan 22 '18 04:01 knoxcard

@knoxcard If you are using Sequelize 4, check out that module:

https://github.com/idangozlan/sequelize-redis

It's a full solution for caching + invalidating cache easily, and as much as I know it's the only Sequelize 4 caching module (right now).

Disclaimer: I'm the author of that module and I'm using that on production for daily traffic of 1m unique users.

idangozlan avatar Jan 22 '18 18:01 idangozlan

You can connect your connection and remove it wit this

await rc.flushdb()

araratmartirossyan avatar Mar 11 '19 18:03 araratmartirossyan