Round robin magic: Raises the current redis server index and returns it
507689
def _raise_server_index(self):
        """"""

        self._current_server_index = (self._current_server_index + 1) % len(self._servers)

        return self._current_server_index
1056756
function(err, results) {

        if (!err) {

          self.sessionSubscriber = new SessionSubscriber(
            self.conf && self.conf.redis && self.conf.redis ? self.conf.redis : undefined,
            self.serverName,
            function(err) {
              if (!err) {

                console.info(' (init) REDIS     is connected  (for pub/sub)');
                console.info('        REDIS     is subscribed (C-' + self.serverName + ')');

                self._startup(server, io);

                if (cb) cb();

              } else {
                console.error(err);
                process.exit(1);
              }
            }
          );

        } else {

          for (var errNum in results) {
            if (results.hasOwnProperty(errNum) && results[errNum]) {
              console.error('  - ' + results[errNum] + '\n');
            }
          }
          process.exit(1);
        }
      }
195357
def _get_redis_server(opts=None):
    '''
    
    '''
    global REDIS_SERVER
    if REDIS_SERVER:
        return REDIS_SERVER
    if not opts:
        opts = _get_redis_cache_opts()

    if opts['cluster_mode']:
        REDIS_SERVER = StrictRedisCluster(startup_nodes=opts['startup_nodes'],
                                          skip_full_coverage_check=opts['skip_full_coverage_check'])
    else:
        REDIS_SERVER = redis.StrictRedis(opts['host'],
                                   opts['port'],
                                   unix_socket_path=opts['unix_socket_path'],
                                   db=opts['db'],
                                   password=opts['password'])
    return REDIS_SERVER
254
def run_checks(collector):
    """"""
    artifact = collector.configuration["dashmat"].artifact
    chosen = artifact
    if chosen in (None, "", NotSpecified):
        chosen = None

    dashmat = collector.configuration["dashmat"]
    modules = collector.configuration["__active_modules__"]
    config_root = collector.configuration["config_root"]
    module_options = collector.configuration["modules"]

    datastore = JsonDataStore(os.path.join(config_root, "data.json"))
    if dashmat.redis_host:
        datastore = RedisDataStore(redis.Redis(dashmat.redis_host))

    scheduler = Scheduler(datastore)

    for name, module in modules.items():
        if chosen is None or name == chosen:
            server = module.make_server(module_options[name].server_options)
            scheduler.register(module, server, name)

    scheduler.twitch(force=True)
921329
function() {
  
  // Redis default configuration
  this.config = {
    port:     6379,
    host:    '127.0.0.1',
    options:  null
  };
    
  // Resque queue base name
  var RESQUE_BASE = 'resque:queue:';
  
  // Queues
  this.queues = {
    post_queue:   RESQUE_BASE+'post_queue',
    delete_queue: RESQUE_BASE+'delete_queue'
  };
  
}
973372
function initRedis(config, callback) {

  var self = this;

  protos.util.checkLocalPort(config.port, function(err) {

    if (err) {
      app.log("RedisTransport [%s:%s] %s", config.host, config.port, err.code);
    } else {

      // Set redis client
      self.client = redis.createClient(config.port, config.host, self.options);

      // Handle error event
      self.client.on('error', function(err) {
        callback.call(self, err);
      });

      // Authenticate if password provided
      if (typeof config.password == 'string') {
        self.client.auth(config.password, function(err, res) {
          if (err) {
            app.log("RedisTransport: [%s:%s] %s", config.host, config.port, err.code);
          } else if (typeof config.db == 'number' && config.db !== 0) {
            self.client.select(config.db, function(err, res) {
              if (err) callback.call(self, err);
              else callback.call(self, null);
            });
          } else {
            callback.call(self, null);
          }
        });
      } else if (typeof config.db == 'number' && config.db !== 0) {
        self.client.select(config.db, function(err, res) {
          callback.call(self, err);
        });
      } else {
        callback.call(self, null);
      }

    }
  });

}
1001129
def next_request(self):
        '''
        
        '''
        t = time.time()
        # update the redis queues every so often
        if t - self.update_time > self.update_interval:
            self.update_time = t
            self.create_queues()
            self.expire_queues()

        # update the ip address every so often
        if t - self.update_ip_time > self.ip_update_interval:
            self.update_ip_time = t
            self.update_ipaddress()
            self.report_self()

        item = self.find_item()
        if item:
            self.logger.debug("Found url to crawl {url}" \
                    .format(url=item['url']))
            try:
                req = Request(item['url'])
            except ValueError:
                # need absolute url
                # need better url validation here
                req = Request('http://' + item['url'])

            try:
                if 'callback' in item and item['callback'] is not None:
                    req.callback = getattr(self.spider, item['callback'])
            except AttributeError:
                self.logger.warn("Unable to find callback method")

            try:
                if 'errback' in item and item['errback'] is not None:
                    req.errback = getattr(self.spider, item['errback'])
            except AttributeError:
                self.logger.warn("Unable to find errback method")

            if 'meta' in item:
                item = item['meta']

            # defaults not in schema
            if 'curdepth' not in item:
                item['curdepth'] = 0
            if "retry_times" not in item:
                item['retry_times'] = 0

            for key in list(item.keys()):
                req.meta[key] = item[key]

            # extra check to add items to request
            if 'useragent' in item and item['useragent'] is not None:
                req.headers['User-Agent'] = item['useragent']
            if 'cookie' in item and item['cookie'] is not None:
                if isinstance(item['cookie'], dict):
                    req.cookies = item['cookie']
                elif isinstance(item['cookie'], basestring):
                    req.cookies = self.parse_cookie(item['cookie'])

            return req

        return None
1212313
def _normalize_index(self, index, pipe=None):
        """"""
        pipe = self.redis if pipe is None else pipe
        len_self = self.__len__(pipe)
        positive_index = index if index >= 0 else len_self + index

        return len_self, positive_index
109058
synchronized long getNextIndex(String server) {
        checkState(role == Role.LEADER, "role:%s", role);
        checkState(self.equals(leader), "self:%s leader:%s", self, leader);
        checkState(serverData.containsKey(server), "server:%s", server);

        return serverData.get(server).nextIndex;
    }
780989
def raise_or_lock(self, key, timeout):
        
        acquired = Lock(
            self.redis,
            key,
            timeout=timeout,
            blocking=self.blocking,
            blocking_timeout=self.blocking_timeout
        ).acquire()

        if not acquired:
            # Time remaining in milliseconds
            # https://redis.io/commands/pttl
            ttl = self.redis.pttl(key)
            raise AlreadyQueued(ttl / 1000.)
1248886
public static function redis()
    {
        // Detect when the PID of the current process has changed (from a fork, etc)
        // and force a reconnect to redis.
        $pid = getmypid();
        if (self::$pid !== $pid) {
            self::$redis = null;
            self::$pid = $pid;
        }

        if (!is_null(self::$redis)) {
            return self::$redis;
        }

        $server = self::$redisServer;
        if (empty($server)) {
            $server = 'localhost:6379';
        }

        if (is_array($server)) {
            require_once dirname(__FILE__) . '/Resque/RedisCluster.php';
            self::$redis = new Resque_RedisCluster($server);
        } else {
            if (strpos($server, 'unix:') === false) {
                list($host, $port) = explode(':', $server);
            } else {
                $host = $server;
                $port = null;
            }
            require_once dirname(__FILE__) . '/Resque/Redis.php';
            $redisInstance = new Resque_Redis($host, $port, self::$password);
            $redisInstance->prefix(self::$namespace);
            self::$redis = $redisInstance;
        }

        if (!empty(self::$redisDatabase)) {
            self::$redis->select(self::$redisDatabase);
        }

        return self::$redis;
    }
346773
def set(msg_id, suffix, value)
      with_failover { redis.set(key(msg_id, suffix), value) }
    end
809353
def get_lock(self, lockname, locktime=60, auto_renewal=False):
        '''  '''
        pid = os.getpid()
        caller = inspect.stack()[0][3]
        try:
            # rl = redlock.Redlock([{"host": settings.REDIS_SERVERS['std_redis']['host'], "port": settings.REDIS_SERVERS['std_redis']['port'], "db": settings.REDIS_SERVERS['std_redis']['db']}, ])
            rl = redis_lock.Lock(self, lockname, expire=locktime, auto_renewal=auto_renewal)
        except:
            if self.logger:
                self.logger.error('Process {0} ({1}) could not get lock {2}. Going ahead without locking!!! {3}'.format(pid, caller, lockname, traceback.format_exc()))
            return False
        try:
            lock = rl.acquire(blocking=False)
        except RedisError:
            return False
        if not lock:
            return False
        else:
            return rl
1229668
def redis(redis_pool = nil)
      if redis_pool
        redis_pool.with { |conn| yield conn }
      else
        Sidekiq.redis { |conn| yield conn }
      end
    end
1244265
def _send_result_to_redis(self, result):
        """"""
        if self.redis_connected:
            self.logger.debug("Sending result to redis")
            try:
                key = "rest:poll:{u}".format(u=result['uuid'])
                self.redis_conn.set(key, json.dumps(result))
            except ConnectionError:
                self.logger.error("Lost connection to Redis")
                self._spawn_redis_connection_thread()
        else:
            self.logger.warning("Unable to send result to redis, not connected")
587034
function RedisPool(opts) {

    if (!(this instanceof RedisPool)) {
        return new RedisPool(opts);
    }

    EventEmitter.call(this);

    opts = opts || {};
    var defaults = {
        host: '127.0.0.1',
        port: '6379',
        max: 50,
        idleTimeoutMillis: 10000,
        reapIntervalMillis: 1000,
        noReadyCheck: false,
        returnToHead: false,
        unwatchOnRelease: true,
        name: 'default',
        log: false,
        slowPool: {
            log: false,
            elapsedThreshold: 25
        },
        emitter: {
            statusInterval: 60000
        },
        commands: []
    };

    this.options = _.defaults(opts, defaults);
    this.pools = {};
    this.elapsedThreshold = this.options.slowPool.elapsedThreshold;

    // add custom Redis commands
    if (this.options.commands && this.options.commands.length) {
        this.options.commands.forEach(function(newCommand) {
            redis.add_command(newCommand);
        });
    }

    var self = this;
    setInterval(function() {
        Object.keys(self.pools).forEach(function(poolKey) {
            var pool = self.pools[poolKey];
            self.emit('status', {
                name: self.options.name,
                db: poolKey,
                count: pool.getPoolSize(),
                unused: pool.availableObjectsCount(),
                waiting:  pool.waitingClientsCount()
            });
        });
    }, this.options.emitter.statusInterval);
}
345568
async def redis(self) -> aioredis.Redis:
        
        # Use thread-safe asyncio Lock because this method without that is not safe
        async with self._connection_lock:
            if self._redis is None:
                self._redis = await aioredis.create_redis_pool((self._host, self._port),
                                                               db=self._db, password=self._password, ssl=self._ssl,
                                                               minsize=1, maxsize=self._pool_size,
                                                               loop=self._loop, **self._kwargs)
        return self._redis