Nodejs uses redis as the cache medium to encapsulate the cache class example, nodejsredis
This example describes the encapsulation cache class implemented by nodejs using redis as the cache medium. We will share this with you for your reference. The details are as follows:
Previously, redis was used as the cache medium under node to encapsulate redis.
First: Install the npm package redis
const redis = require('redis');
Second: encapsulate
// Cache. jsconst redis = require ('redis '); const config = require ('config'); const logger = require ('winston'); const redisObj = {client: null, connect: function () {this. client = redis. createClient (config. redis); this. client. on ('error', function (err) {logger. error ('rediscache error' + err) ;}); this. client. on ('ready', function () {logger.info ('rediscache connection succeed') ;}, init: funct Ion () {this. connect (); // create a connection const instance = this. client; // rewrite the three methods. It can be defined as needed. Const get = instance. get; const set = instance. set; const setex = instance. setex; instance. set = function (key, value, callback) {if (value! = Undefined) {set. call (instance, key, JSON. stringify (value), callback) ;}}; instance. get = function (key, callback) {get. call (instance, key, (err, val) =>{ if (err) {logger. warn ('redis. get: ', key, err);} callback (null, JSON. parse (val) ;};}; // you do not need to pass the expires parameter. Configure in the config file. Instance. setex = function (key, value, callback) {if (value! = Undefined) {setex. call (instance, key, config. cache. maxAge, JSON. stringify (value), callback) ;}; return instance ;},}; // A redis instance is returned. client instance module. exports = redisObj. init ();
How to use
const cache = require('./cache');cache.get(key, (err, val) => { if (val) { // do something } else { // do otherthing }});cache.set(key, val, (err, res) => { // do something});cache.setex(key, val, (err, res) => { // do something})
I hope this article will help you design nodejs programs.