How to use ioredis - 10 common examples

To help you get started, we’ve selected a few ioredis examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github socketio / socket.io-redis / test / ioredis.js View on Github external
function create(nsp, fn){
    var srv = http();
    var sio = io(srv);
    sio.adapter(adapter({
      pubClient: redis(),
      subClient: redis(null, null, { return_buffers: true }),
      subEvent: 'messageBuffer'
    }));
    srv.listen(function(err){
      if (err) throw err; // abort tests
      if ('function' == typeof nsp) {
        fn = nsp;
        nsp = '';
      }
      nsp = nsp || '/';
      var addr = srv.address();
      var url = 'http://localhost:' + addr.port + nsp;
      fn(sio.of(nsp), ioc(url));
    });
  }
github lawrips / redis-live / index.js View on Github external
var commands = require('./lib/modules/commands');


app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars'); 
app.use(express.static('lib/public'));
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
})); 
console.log(nconf.get('cluster'))

app.listen(9999);

let cluster = new Redis.Cluster(nconf.get('cluster'), 
{
    redisOptions: nconf.get('options')
});

app.get('/', (req, res) => {
    let hosts = nconf.get('cluster').map((i) => i.host + ':' + i.port);
    return res.render('index', {commands: JSON.stringify(commands.get()), hosts: JSON.stringify(hosts)});
});

app.post('/info', (req, res) => {
    let redisOptions = nconf.get('options');
    redisOptions.host = req.body.host.split(':')[0];
    redisOptions.port = req.body.host.split(':').length > 1 ? req.body.host.split(':')[1] : 6379;
    let redis = new Redis(redisOptions);

    redis.info((err, result) => {
github joeferner / redis-commander / bin / redis-commander.js View on Github external
function startAllConnections() {
  try {
    myUtils.validateConfig();
  }
  catch(e) {
    console.error(e.message);
    process.exit(2);
  }

  // redefine keys method before connections are started
  if (config.get('redis.useScan')) {
    console.log('Using scan instead of keys');
    Object.defineProperty(Redis.prototype, 'keys', {
      value: function(pattern, cb) {
        let keys = [];
        let that = this;
        let scanCB = function(err, res) {
          if (err) {
            if (typeof cb === 'function') cb(err);
            else {
              console.log('ERROR in redefined "keys" function to use "scan" instead without callback: ' +
                  (err.message ? err.message : JSON.stringify(err)));
            }
          }
          else {
            let count = res[0], curKeys = res[1];
            console.log("scanning: " + count + ": " + curKeys.length);
            keys = keys.concat(curKeys);
            if (Number(count) === 0) {
github coralproject / talk / services / redis.js View on Github external
const createClient = () => {
  let client;
  if (REDIS_CLUSTER_MODE === 'NONE') {
    client = new Redis(
      REDIS_URL,
      merge({}, REDIS_CLIENT_CONFIG, {
        retryStrategy,
      })
    );
  } else if (REDIS_CLUSTER_MODE === 'CLUSTER') {
    client = new Redis.Cluster(
      REDIS_CLUSTER_CONFIGURATION,
      merge(
        {
          scaleReads: 'slave',
        },
        REDIS_CLIENT_CONFIG,
        {
          clusterRetryStrategy: retryStrategy,
        }
      )
    );
  }

  // Attach the monitors that will print debug messages to the console.
  attachMonitors(client);
github microsoft / devops-project-samples / node / express / kubernetes / Application / routes / index.js View on Github external
'use strict';
var express = require('express');
var router = express.Router();
var redis = require('ioredis');

var redisServer = process.env.redis_server || 'redis-cache';

console.log("Trying to create redis client");
var client = redis.createClient(6379, redisServer);

console.log("Redis Client created");

/* GET home page. */
router.get('/', function (req, res) {
  console.log("Index route");
  client.incr('viewCount', function (err, result) {
    res.render('index', { message: "Total Visits: " + result });
  });
});

module.exports = router;
github seerline / clchart / cs / server.js View on Github external
function from_client_to_server (message, argv) {
  message.id = argv[0]
  let com = argv[1]
  let param = argv.slice(2)

  console.log(param)
  let command = new class_redis_command(com, param, // {},
    {
      replyEncoding: 'utf8'
    },
    function (error, result) {
      console.log(':::', typeof result, result, arguments.length)
      from_server_to_client(message, result)
      for (var i = 0; i < arguments.length; i++) {
        console.log(i, '--------:' + arguments[i])
      }
    })
  server.redis_server.sendCommand(command)
  }
github redibox / core / src / core.js View on Github external
this._clientCount = 0;
    this._allClientCount = 0;
    this.bootedAtTimestamp = Date.now();
    this.options = mergeDeep(defaults(), options);
    this.log = createLogger(this.options.log);
    this.options.redis.cluster = !!this.options.redis.hosts && this.options.redis.hosts.length > 0;

    // setup connection timeout
    const connectionFailedTimer = setTimeout(() => {
      const error = new Error('Failed to connect to redis, please check your config / servers.');
      this.handleError(error);
      callback(error);
    }, this.options.redis.connectionTimeout);

    // https://github.com/luin/ioredis#error-handling
    Redis.Promise.onPossiblyUnhandledRejection(this.handleError);

    this.once(this.toEventName('client:default:ready'), () => {
      clearTimeout(connectionFailedTimer);
      // create a ref to default client for niceness
      this.client = this.clients.default;
      hookLoader(this)
        .then(() => {
          this.trumpWall();
          this.emit('ready');
          this.notifyHooks();
          callback();
        }, this.handleError).catch(this.handleError);
    });

    this.createClient('default');
    process.once('SIGTERM', this.quit);
github vpdb / server / src / state.ts View on Github external
private setupRedis(): IORedis.Redis {
		return new IORedis({
			port: config.vpdb.redis.port,
			host: config.vpdb.redis.host,
			family: 4,           // 4 (IPv4) or 6 (IPv6)
			db: config.vpdb.redis.db,
		});
	}
}
github ruojs / ruo / src / ws.js View on Github external
function createWebSocketApplication (server, api, options) {
  if (!options) {
    return
  }

  const io = require('socket.io')(server, {path: options.path})
  const wsapp = express()
  wsapp.io = io
  wsapp.extendMiddleware = extendMiddleware

  if (options.session) {
    if (options.session.redis) {
      const redis = options.session.redis
      // pub and sub shuold not use the same instance
      const pubClient = Array.isArray(redis) ? new Redis.Cluster(redis) : new Redis(redis)
      const subClient = Array.isArray(redis) ? new Redis.Cluster(redis) : new Redis(redis)
      io.adapter(ioRedis({
        key: `${rc.name}:socket.io`,
        pubClient: pubClient,
        subClient: subClient,
        subEvent: 'messageBuffer'
      }))
    }
    io.use(ioSession(createSession(options.session)))
  }

  io.on('connection', (socket) => {
    const session = socket.handshake.session
    // join sid and userId to allow send message to particular socket
    socket.join(`session ${session.id}`)
    // TODO: custom userId field?
    socket.join(`user ${session.userId}`)
github an-sh / chat-service / src / RedisState.js View on Github external
'use strict'

const Buffer = require('safe-buffer').Buffer
const ChatServiceError = require('./ChatServiceError')
const Promise = require('bluebird')
const Redis = require('ioredis')
const Room = require('./Room')
const User = require('./User')
const _ = require('lodash')
const promiseRetry = require('promise-retry')
const uid = require('uid-safe')
const { mixin } = require('./utils')

Redis.Promise = require('bluebird')

const namespace = 'chatservice'

function initSet (redis, set, values) {
  return redis.del(set)
    .then(() => values ? redis.sadd(set, values) : null)
}

// State init/remove operations.
class StateOperations {
  constructor (name, exitsErrorName, redis, makeKeyName, stateReset) {
    this.name = name
    this.exitsErrorName = exitsErrorName
    this.redis = redis
    this.makeKeyName = makeKeyName
    this.stateReset = stateReset

ioredis

A robust, performance-focused and full-featured Redis client for Node.js.

MIT
Latest version published 8 days ago

Package Health Score

98 / 100
Full package analysis