Using Predix Cache with NodeJS

Get code samples and recommended libraries for using a Predix Cache service with NodeJS.

Recommended Library
io-redis. See https://github.com/luin/ioredis
Alternative Libraries
node-redis. See https://github.com/NodeRedis/node_redis

Code Samples Using ioredis Library

To install the library, include ioredis and vcap_services modules in your application's dependencies:
npm init
  npm install ioredis --save
  npm install vcap_services --save
Sample of the Updated package.json file
{
  "name": "redis-single-sample",
  "version": "0.1.0",
  "description": "Sample application for single node redis instance",
  "main": "redis-single-sample.js",
  "scripts": {
    "start": "node redis-single-sample.js"
  },
  "author": "GE Digital",
  "license": "ISC",
  "dependencies": {
    "ioredis": "^3.0.0",
    "vcap_services": "^0.3.4"
  }
}
Sample of Cloud Foundry manifest
applications:
  - name: redis-sample
    command: node redis-single-sample.js
    mem: 256M
    disk: 1024M
    instances: 1
    services:
      - redis-single-sample
ioredis Sample for Shared and Dedicated single node Service Plans
var vcap_services = require('vcap_services');
  var Redis = require('ioredis');

  var credentials = vcap_services.getCredentials('predix-redis', 'Free');
  console.log(credentials);

  var redis = new Redis({
   port: credentials.port,                // Redis port
   host: credentials.host,                // Redis host
   password: credentials.password         // Redis pass
  })

  redis.set('foo', 'bar');
  redis.get('foo', function (err, result) {
   console.log(result);
  });
ioredis Sample for High Availability Service Plans using Sentinels
 var vcap_services = require('vcap_services');
   var Redis = require('ioredis');

   var credentials = vcap_services.getCredentials('predix-redis', 'Gold');
   console.log(credentials);

   var sentinels = credentials.ip_list;

   var redis = new Redis({
     sentinels: [
       { host: sentinels[0], port: credentials.sentinel_port },
       { host: sentinels[1], port: credentials.sentinel_port },
       { host: sentinels[2], port: credentials.sentinel_port }
     ],
     name: credentials.master_name,
     password: credentials.password
   });

   redis.set('foo', 'bar');
   redis.get('foo', function (err, result) {
     console.log(result);
   });

Validating Connectivity

To verify the application is able to connect, look at the log output by using:
cf logs redis-sample --recent
Output example:
[DEA/121] OUT Starting app instance (index 0) with guid 691ae1e8-3884-4771-9c4f-f2a3c8a1cc45
[App/0] OUT { host: '172.72.9.249',
[App/0] OUT   port: 6379,
[App/0] OUT   password: 'REDACTED',
[App/0] OUT   master_name: 'cf-svc-redis-clustered-prod-9e0757fc-9813-4034-9496-097a2aa8469b',
[App/0] OUT   sentinel_port: 16379,
[App/0] OUT   ip_list: [ '172.72.8.161', '172.72.9.249', '172.72.8.162' ] }
[App/0] OUT bar

See io-redis Sentinel for additional Sentinel documentation.