joshbetz / node-memcached

A Memcached client for modern Node.js with consistent hashing and connection pooling.
4 stars 0 forks source link
memcached memcached-client nodejs

Memcached Node.js CI

There are three libraries exported from this package.

const { Memcached, Pool, HashPool } = require( '@joshbetz/memcached' );

API

The API for all three libraries is the same. It just depends what kind of connection and failover logic you need.

async ready()

Wait for the connection to be ready.

async flush()

Flush the Memcached data.

async set( key, value, ttl ): Boolean

SETs a given key and value for the specified TTL (or no TTL). Returns a Boolean to indicate whether the operation was successful.

async add( key, value, ttl ): Boolean

ADDs a given key and value for the specified TTL (or no TTL) if it doesn't already exist. Returns a Boolean to indicate whether the operation was successful.

async get( key ): string|Boolean

GETs a given key. Returns false if it does not exist.

async del( key ): Boolean

DELETEs a given key.

async ping(): Boolean

Sends the version command. Returns true if the expected response is returned.

async end()

Close the connection to Memcached.

Memcached Library

This is a simple Memcached library that connects to a Memcached server and execute commands.

Example

const opts = {
    prefix: '',
    socketTimeout: 100,
};
const memcached = new Memcached( 11211, 'localhost', opts );
await memcached.ready();
await memcached.set( 'key', 'value' );
const value = await memcached.get( 'key' );
await memcached.end();

Options

Pool Library

This is a wrapper around our Memcached library that establishes a connection pool.

Example

const opts = {
    // Pool options
    max: 10,
    min: 2,
    acquireTimeoutMillis: 200,
    destroyTimeoutMillis: 200,
    maxWaitingClients: 2,
    idleTimeoutMillis: 30000,

    // Connection options
    prefix: '',
    socketTimeout: 100,
};
const memcached = new Pool( 11211, 'localhost', opts );
await memcached.set( 'key', 'value' );
const value = await memcached.get( 'key' );
await memcached.end();

Options

HashPool Library

This is a wrapper around our Pool library that establishes connection pools to each host and load balances queries across them. It includes automatic failover and reconnecting when hosts experience issues.

Example

const opts = {
    retry: ( retries: number ): number => {
        const exp = Math.pow( 2, retries ) * 250;

        // exponential backoff up to 30 seconds
        return Math.min( exp, 30000 );
    },

    // Pool options
    max: 10,
    min: 2,
    acquireTimeoutMillis: 200,
    destroyTimeoutMillis: 200,
    maxWaitingClients: 2,
    idleTimeoutMillis: 30000,

    // Connection options
    prefix: '',
    socketTimeout: 100,
};
const memcached = new HashPool( [ 'localhost:11211', 'localhost:11311' ], opts );
await memcached.set( 'key', 'value' );
const value = await memcached.get( 'key' );
await memcached.end();

Options