View source
<?php
namespace Drupal\redis\Queue;
class Predis extends QueueBase {
protected $client;
public function __construct($name, array $settings, \Predis\Client $client) {
parent::__construct($name, $settings);
$this->client = $client;
}
public function createItem($data) {
$record = new \stdClass();
$record->data = $data;
$record->qid = $this
->incrementId();
$record->timestamp = time();
if (!$this->client
->hsetnx($this->availableItems, $record->qid, serialize($record))) {
return FALSE;
}
$start_len = $this->client
->lLen($this->availableListKey);
if ($start_len < $this->client
->lpush($this->availableListKey, $record->qid)) {
return $record->qid;
}
}
protected function incrementId() {
return $this->client
->incr($this->incrementCounterKey);
}
public function numberOfItems() {
return $this->client
->lLen($this->availableListKey) + $this->client
->lLen($this->claimedListKey);
}
public function claimItem($lease_time = 30) {
$this
->garbageCollection();
$item = FALSE;
if ($this->reserveTimeout !== NULL) {
$qid = $this->client
->brpoplpush($this->availableListKey, $this->claimedListKey, $this->reserveTimeout);
}
else {
$qid = $this->client
->rpoplpush($this->availableListKey, $this->claimedListKey);
}
if ($qid) {
$job = $this->client
->hget($this->availableItems, $qid);
if ($job) {
$item = unserialize($job);
$this->client
->setex($this->leasedKeyPrefix . $item->qid, $lease_time, '1');
}
}
return $item;
}
public function releaseItem($item) {
$this->client
->lrem($this->claimedListKey, -1, $item->qid);
$this->client
->lpush($this->availableListKey, $item->qid);
}
public function deleteItem($item) {
$this->client
->lrem($this->claimedListKey, -1, $item->qid);
$this->client
->lrem($this->availableListKey, -1, $item->qid);
$this->client
->hdel($this->availableItems, $item->qid);
}
public function deleteQueue() {
$keys_to_remove = [
$this->claimedListKey,
$this->availableListKey,
$this->availableItems,
$this->incrementCounterKey,
];
foreach ($this->client
->keys($this->leasedKeyPrefix . '*') as $key) {
$keys_to_remove[] = $key;
}
$this->client
->del($keys_to_remove);
}
protected function garbageCollection() {
foreach ($this->client
->lrange($this->claimedListKey, 0, -1) as $qid) {
if (!$this->client
->exists($this->leasedKeyPrefix . $qid)) {
$this->client
->lrem($this->claimedListKey, $qid, -1);
$this->client
->lpush($this->availableListKey, $qid);
}
}
}
}