How to use redis - 10 common examples

To help you get started, we’ve selected a few redis 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 launchdarkly / node-server-sdk / test-types.ts View on Github external
client.allFlags(user, (flagSet: ld.LDFlagSet) =>  {
  var flagSetValue: ld.LDFlagValue = flagSet['key'];
});

// evaluation methods with promises
client.variation('key', user, false).then((value: ld.LDFlagValue) => { });
client.variation('key', user, 2).then((value: ld.LDFlagValue) => { });
client.variation('key', user, 'default').then((value: ld.LDFlagValue) => { });
client.variationDetail('key', user, 'default').then((detail: ld.LDEvaluationDetail) => { });
client.allFlags(user).then((flagSet: ld.LDFlagSet) => { });

// Redis integration
var redisStore0 = ld.RedisFeatureStore();
var myRedisOpts: redis.ClientOpts = {};
var redisStore1 = ld.RedisFeatureStore(myRedisOpts, 30, 'prefix', logger);
var myRedisClient: redis.RedisClient = new redis.RedisClient(myRedisOpts);
var redisStore2 = ld.RedisFeatureStore(undefined, 30, 'prefix', logger, myRedisClient);
github nicobarray / aquedux / packages / aquedux-server / __tests__ / server.js View on Github external
import http from 'http'
import { applyMiddleware } from 'redux'

import redis from 'redis'
import bluebird from 'bluebird'

bluebird.promisifyAll(redis.RedisClient.prototype)
bluebird.promisifyAll(redis.Multi.prototype)

import { until, once, fakeUserAction } from './utils'

// Public api
import { createAquedux, createStore, close } from '../src'

// Private
import configManager from '../src/managers/configManager'
import channelManager from '../src/managers/channelManager'
import tankManager from '../src/managers/tankManager'
import queueManager from '../src/managers/queueManager'

const counterReducer = (prevState = 0, action) => {
  const { type } = action
  if (type === 'counter/inc') {
github acruikshank / redis-waiting-list-demo / server.js View on Github external
applicationServer.listen( port );
  console.log( "Listening on port " + port );


  /*************************
   * Web Socket Communication
   *************************/

  // Initialize socket.io using redis store
  var io = sockets.listen( applicationServer );
  io.set( 'log level', 2 );

  // Use redis store to support multi-process/server communication
  var RedisStore = require('socket.io/lib/stores/redis');
  io.set('store', new RedisStore({
    redisPub : redis.createClient(),
    redisSub : redis.createClient(),
    redisClient : redis.createClient()
  }));

  function updateRoomCount( roomId ) {
    return participation.count(roomId, withCount);

    function withCount( err, count ) {
      if ( err )
        return console.log(err);

      io.sockets.in(roomId).json.emit('message', {count:count})
    }
  }

  // Use join message to register as a participant
github FeelTrainCoop / supermute / lib / classes / stream.js View on Github external
};
      this.userid = profile.id_str;
      let creds = userdata.credentials;
      // use the application's consumer stuff but the user's access stuff
      creds.consumer_key = this.app.get('twitterCredentials').consumer_key;
      creds.consumer_secret = this.app.get('twitterCredentials').consumer_secret;
      console.log(creds);
      this.T = new Twit(creds);

      // This user doesn't exist in the DB yet so we create a blank entry
      // and include the new keyword and expiration date
      // mutedUsers and isExpired are empty because we're intializing
      if (!exists) {
        console.log(`writing ${profile.id_str} to database...`);
        // TODO hash our application credentials???? maybe??
        client.hset(`supermute-users`, profile.id_str, JSON.stringify(userdata), redis.print);
        // save our userdata to this stream object
        this.userdata = userdata;
      }
      else {
        // do nothing
      }

      // start the stream
      this.start(UNMUTE);
    });
  }
github aboutlo / async-memo-ize / packages / async-memo-ize-plugin-redis-cache / lib / index.js View on Github external
constructor() {
    const args = Array.from(arguments)
    if (args[0] instanceof redis.RedisClient) {
      this.client = args[0]
      this.localCache = new LocalCache()
    } else if (args[0] instanceof LocalCache) {
      this.localCache = args[0]
      this.client = redis.createClient.apply(redis, args.splice(1))
    } else if (
      args[0] instanceof Object &&
      !args[0] instanceof redis.RedisClient &&
      args.length === 1
    ) {
      this.localCache = args.localCache
      const redisOptions = omit(args, ['localCache'])
      this.client = redis.createClient(redisOptions)
    } else {
      this.client = redis.createClient.apply(redis, args)
      this.localCache = new LocalCache()
    }

    this.client.on('error', function(err) {
      console.log('Error ' + err)
    })
    this.client.on('ready', function() {
      // console.log('ready')
    })
github snodgrass23 / base12 / lib / redis / index.js View on Github external
if (app.config.redistogo_url) {
    try {
      var redis_connection = url.parse(app.config.redistogo_url);
      config = {
        host: redis_connection.hostname,
        port: redis_connection.port,
        auth: redis_connection.auth
      };
    }
    catch(e) {
      // error pulling redis_togo params
      console.log('Error pulling redis_togo params from ENV', app.config.redistogo_url, e);
    }
  }

  redis.debug_mode = config.debug;

  var client = redis.createClient(config.port, config.host);
  if (config.auth) {
    var auth = (config.auth.indexOf(":") > 0) ? config.auth.split(":")[1] : config.auth;
    client.auth(auth);
  }
  if (config.db) client.select(config.db);
  app.redis = client;

  client.on("ready", function() {
    console.log("Redis connected to: redis://"+config.host+":"+config.port);
  });

  client.on("error", function() {
    console.log("Error: Redis could not connect to: redis://"+config.host+":"+config.port);
  });
github Wikia / app / extensions / wikia / Chat / js / server.js View on Github external
rc.llen(chatEntriesInRoomKey, function(err, len){
		if(err){
			console.log("Error: while trying to get length of list of messages in '" + chatEntriesInRoomKey + "'. Error msg: " + err);
		} else if( len > config.MAX_MESSAGES_IN_BACKLOG + 1 ){
			console.log("Found a bunch of extra messages in '" + chatEntriesInRoomKey + "'.  Getting rid of the oldest " + (len - config.MAX_MESSAGES_IN_BACKLOG) + " of them.");
			rc.ltrim(chatEntriesInRoomKey, (-1 * config.MAX_MESSAGES_IN_BACKLOG), -1, redis.print);
		} else if( len == (config.MAX_MESSAGES_IN_BACKLOG + 1)){
			// This seems like it'd be faster than ltrim even though ltrim says it's O(N) where N is number to remove and this is O(1).
			console.log("Trimming extra entry from list of messages in '" + chatEntriesInRoomKey + "'");
			rc.lpop(chatEntriesInRoomKey, redis.print);
		}
	});
	console.log("Done pruning any old messages in room (if needed).");
github fabioberger / Mobile-Live-Chat-Support-Server / pub.js View on Github external
var redis = require("redis");
var agent = redis.createClient();
var agent2 = redis.createClient();

redis.debug_mode = false;

// Most clients probably don't do much on "subscribe".  This example uses it to coordinate things within one program.
agent.on("subscribe", function (channel, count) {
    console.log("agent subscribed to " + channel + ", " + count + " total subscriptions");
});

agent.on("unsubscribe", function (channel, count) {
    console.log("agent unsubscribed from " + channel + ", " + count + " total subscriptions");
    if (count === 0) {
        customer.end();
        agent.end();
    }
});

agent.on("message", function (channel, message) {
    var msg = JSON.parse(message);
github TheBrousse / TitaniumMobileHotshot / 07-SecondToLastFantasyOnlineServer / node_modules / socket.io / node_modules / redis / examples / pub_sub.js View on Github external
var redis = require("redis"),
    client1 = redis.createClient(), msg_count = 0,
    client2 = redis.createClient();

redis.debug_mode = false;

// Most clients probably don't do much on "subscribe".  This example uses it to coordinate things within one program.
client1.on("subscribe", function (channel, count) {
    console.log("client1 subscribed to " + channel + ", " + count + " total subscriptions");
    if (count === 2) {
        client2.publish("a nice channel", "I am sending a message.");
        client2.publish("another one", "I am sending a second message.");
        client2.publish("a nice channel", "I am sending my last message.");
    }
});

client1.on("unsubscribe", function (channel, count) {
    console.log("client1 unsubscribed from " + channel + ", " + count + " total subscriptions");
    if (count === 0) {
        client2.end();
        client1.end();
github mcamac / crosswords / server / server.js View on Github external
var logfmt = require('logfmt');
var passport = require('passport');
var mongoose = require('mongoose');
var redis = require('redis');
var RedisStore = require('connect-redis')(session);
var busboy = require('connect-busboy');


mongoose.connect(process.env.MONGOHQ_URL || 'mongodb://localhost');

if (process.env.REDISTOGO_URL) {
   // inside if statement
  var rtg   = require("url").parse(process.env.REDISTOGO_URL);
  var redis = require("redis").createClient(rtg.port, rtg.hostname);

  redis.auth(rtg.auth.split(":")[1]);
} else {
  var redis = require("redis").createClient();
}

// redis.sadd('guests', 'g1');

var sessionStore = new RedisStore({ client: redis });

var app = express();

app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.use('/static', express.static(__dirname + '/../static'));

app.use(cookieParser());
app.use(busboy());