rfink / sequelize-redis-cache

Small fluent interface for caching sequelize database query results in redis more easily
MIT License
174 stars 47 forks source link

How to clear cache? #37

Open btimeteam opened 6 years ago

btimeteam commented 6 years ago

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();
};
rfink commented 6 years ago

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.

knoxcard commented 6 years ago

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.

idangozlan commented 6 years ago

@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.

araratmartirossyan commented 5 years ago

You can connect your connection and remove it wit this

await rc.flushdb()