public function add($id, $value, $ttl = null) { try { $this->redis->setnx($id, $value); if ($ttl) { $this->redis->expire($id, $ttl); } return true; } catch (Predis\PredisException $e) { return false; } }
/** * Make sure, the Redis keys exist. * * @return void */ private function initializeRedis() { if ($this->initialized) { return; } $this->hash = substr(sha1(serialize($this->items)), 0, 8); $positionKey = $this->getKeyForCurrentPosition(); $existing = !$this->redis->setnx($positionKey, count($this->items) - 1); if (!$existing && count($this->items)) { $listKey = $this->getKeyForItemList(); $this->itemCount = $this->redis->rpush($listKey, $this->items); } $this->initialized = true; }
public function work() { foreach ($this->limits as $index => $limit) { $counterName = "queue:{$this->tube}:throttle:{$index}"; $started = (bool) $this->redis->setnx($counterName, $limit['requests']); $counter = $this->redis->get($counterName); if ($started) { $this->redis->transaction(function (MultiExec $transaction) use($counterName, $limit) { $transaction->expire($counterName, $limit['seconds']); $transaction->decr($counterName); }); } else { if ($counter > 1) { $this->redis->decr($counterName); } else { $this->pheanstalk->pauseTube($this->tube, $this->redis->ttl($counterName)); } } } }
private function lockSession($sessionId) { $attempts = 1000000 / $this->spinLockWait * $this->lockMaxWait; $this->lockKey = $sessionId . '.lock'; for ($i = 0; $i < $attempts; $i++) { $success = $this->redis->setnx($this->prefix . $this->lockKey, '1'); if ($success) { $this->locked = true; $this->redis->expire($this->prefix . $this->lockKey, $this->lockMaxWait + 1); return true; } usleep($this->spinLockWait); } return false; }
/** * Create nonce for server and salt, expiring after * $Auth_OpenID_SKEW seconds. */ function useNonce($server_url, $timestamp, $salt) { global $Auth_OpenID_SKEW; // save one request to memcache when nonce obviously expired if (abs($timestamp - time()) > $Auth_OpenID_SKEW) { return false; } // SETNX will set the value only of the key doesn't exist yet. $nonceKey = $this->nonceKey($server_url, $salt); $added = $this->redis->setnx($nonceKey, "1"); if ($added) { // Will set expiration $this->redis->expire($nonceKey, $Auth_OpenID_SKEW); return true; } else { return false; } }