Browse Source

dev 2020-11

Max F 5 years ago
parent
commit
f07ee9526e
2 changed files with 88 additions and 1 deletions
  1. 87 0
      src/Database/Redis/RedisQueue.php
  2. 1 1
      src/Http/Request.php

+ 87 - 0
src/Database/Redis/RedisQueue.php

@@ -0,0 +1,87 @@
+<?php
+
+namespace KarmaFW\Database\Redis;
+
+
+class RedisQueue
+{
+	protected $redis;
+	protected $queue_name;
+
+
+	function __construct(Redis $redis, $queue_name)
+	{
+		$this->redis = $redis;
+		$this->queue_name = $queue_name;
+	}
+
+
+	function getRedis()
+	{
+		return $this->redis;
+	}
+
+	function getClient()
+	{
+		return $this->redis->getClient();
+	}
+
+	function push($data)
+	{
+		$data = serialize($data);
+		$client = $this->redis->getClient();
+		$client->rPush($this->queue_name, $data);
+	}
+
+	function unshift($data)
+	{
+		$data = serialize($data);
+		$client = $this->redis->getClient();
+		$client->lPush($this->queue_name, $data);
+	}
+
+	function pop($timeout=0)
+	{
+		$ts_start = microtime(true);
+		$client = $this->redis->getClient();
+		$data = null;
+
+		while (! $data) {
+			$data_raw = $client->rPop($this->queue_name);
+			if ($data_raw) {
+				$data = unserialize($data_raw);
+				break;
+			}
+
+			$ts_end = microtime(true);
+			$duration = $ts_end - $ts_start;
+			if ($duration > $timeout) {
+				break;
+			}
+		}
+		return $data;
+	}
+
+	function shift($timeout=0)
+	{
+		$ts_start = microtime(true);
+		$client = $this->redis->getClient();
+		$data = null;
+
+		while (! $data) {
+			$data_raw = $client->lPop($this->queue_name);
+			if ($data_raw) {
+				$data = unserialize($data_raw);
+				break;
+			}
+
+			$ts_end = microtime(true);
+			$duration = $ts_end - $ts_start;
+			if ($duration > $timeout) {
+				break;
+			}
+		}
+		return $data;
+	}
+
+}

+ 1 - 1
src/Http/Request.php

@@ -221,7 +221,7 @@ class Request
 
 	public function isAjax()
 	{
-		return (! empty($request->SERVER['HTTP_X_REQUESTED_WITH']) && $request->SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
+		return (! empty($this->SERVER['HTTP_X_REQUESTED_WITH']) && $this->SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
 	}