user6281125
user6281125

Reputation: 11

Self expirable cache in node.js

I want to cache bunch of records, the records will be invalid after some minutes, To improve performance I want go with in memory database.

it is just a key value, key is the string, value is json object.

It have to centralized and scalable to multiple nodes, it will be accessed by Node.JS API and web applications

Looking for a kind of solution

  1. In memory cache
  2. Retrieve value by key
  3. Solution can be scaled to multiple nodes
  4. The key have to expire after the duration

Current solution

  1. mysql table

  2. Each record contains the expiration time, based on that I'm ignoring the record

  3. A service will delete the expired records periodically

Upvotes: 1

Views: 3586

Answers (2)

AJS
AJS

Reputation: 2023

I would suggest go with redis one of the most widely used in memory databases that scales really well and should serve your purpose as you could set ttl (time to live).

Upvotes: 2

vorillaz
vorillaz

Reputation: 6266

You can use lru cache module.

var LRU = require("lru-cache")
  , options = { max: 500
              , length: function (n, key) { return n * 2 + key.length }
              , dispose: function (key, n) { n.close() }
              , maxAge: 1000 * 60 * 60 }
  , cache = LRU(options)
  , otherCache = LRU(50) // sets just the max size

cache.set("key", "value")
cache.get("key") // "value"

// non-string keys ARE fully supported
var someObject = {}
cache.set(someObject, 'a value')

Upvotes: 2

Related Questions