mem.js
I am using mem.js as client library for accessing memcached. To use it, the first thing to do is to add the requirement to your package.json:
npm install memjs --save
MemcachedFactory
Then we can create a simple helper class to have an abstraction layer between our code and the library itself.
1. Create a folder in /app named classes
2. Create a new file with the name MemcachedFactory.js
3. Add the following code:
const memjs = require('memjs');
/**
* Helper class for using Memcache
*
* @author Sven Hasselbach
* @version 0.1
*/
class MemcachedFactory {
constructor() {
this.client = memjs.Client.create('127.0.0.1:11211');
}
/**
* returns a single instance of the class
*/
static getInstance() {
if (this.instance == null) {
this.instance = new MemcachedFactory();
}
return this.instance;
}
/**
* stores a value in memcache
* @param {string} key
* the key used
* @param {*} value
* the value to store
* @param {number} ttl
* time-to-live in seconds
*/
set(key, value, ttl) {
this.client.set(key, value, { expires: ttl }, err => {
if (err) {
console.log(err);
throw err;
}
});
}
/**
* gets a value from memcache
*
* @param {string} key
* the key used
* @param {function} callback
* the callback containing the value
*/
get(key, callback) {
this.client.get(key, (err, value) => {
if (err) {
console.error(err);
callback(err);
}
if (value == null) {
callback(err, null);
} else {
callback(err, value.toString());
}
});
}
}
module.exports = MemcachedFactory;
5. To use the class in our code, we have to add the requirement first:
const mf = require('../classes/MemcachedFactory');
6. Here is a small example how the class is used:
mf.getInstance().get(key, (error, value) => {
if (error) {
// handle error here
}else{
// we have a value
console.log(`The value is ${value}`);
}
});
The getInstance method returns an instance of the class. Then the get method is used with the key to retreive, and a callback method which is called when the request to memcached is completed.
The set method allows to put a key to memcached, and with ttl we can define how long the key is valid and stored.