-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathMyjobsWithRedis.php
82 lines (70 loc) · 1.78 KB
/
MyjobsWithRedis.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
/**
* myjobs sample code using Redis
*
* This sample library mixed Redis client connection, which you can separate into components in
* actual development.
*
* @author Nick Tsai <myintaer@gmail.com>
* @package https://github.com/nrk/predis
*/
class MyjobsWithRedis
{
/**
* Redis key
*/
const QUEUE_KEY = 'your-job-key';
/**
* Redis client
*
* @var Predis\Client
*/
protected $redisClient;
function __construct()
{
// You can store Redis config into application config, for example: `$this->CI->config->item('redis', 'services');`
$this->redisClient = new Predis\Client(['host'=>'yourHostOrIP', 'scheme'=>'tcp', 'port'=>6379], ['parameters'=>['password'=>'yourpass']]);
// Connection check
try {
$this->redisClient->type('test');
} catch (Predis\Connection\ConnectionException $e) {
if (ENVIRONMENT=='development') {
throw $e;
}
// Prevent further error
exit;
}
}
/**
* Check if there are any jobs from Redis queue
*
* @return boolean
*/
public function exists()
{
return $this->redisClient->exists(self::QUEUE_KEY);
}
/**
* Pop up a job from Redis queue
*
* @return array
*/
public function popJob()
{
// Assume storing JSON string data in queue
// Using LPOP or RPOP depends on your producer push
$taskJSON = $this->redisClient->lpop(self::QUEUE_KEY);
return json_decode($taskJSON, true);
}
/**
* Process a job
*
* @param array $job
* @return boolean
*/
public function processJob($job)
{
// Your own job process here
return true;
}
}