This is a practice report showing how Redis, an in-memory data structure store, can be used in distributed environments to communicate, coordinate and to share state.
The talk contains a small introduction to Redis and shows how it can be used in Perl by highlighting key implementation details of a productively used job scheduling system.
48. Job Lock (simple)
redis> SET job:2:lock whatever NX
"OK"
redis> SET job:2:lock whatever NX
(Nil)
redis> DEL job:2:lock
(integer) 1
redis> SET job:2:lock whatever NX
"OK"
redis>
49. Job Lock (timeout)
redis> SET job:2:lock unique_nounce_ao45u89 EX 3600 NX
"OK"
redis> SET job:2:lock sl8ts90eu EX 3600 NX
(Nil)
redis>
Unlock:
run serverside Lua code to delete the key if the nouce is still correct
(https://redis.io/commands/set)
50. 01 sub pick_pending_job {
02 my ($r) = @_;
03 # get jobs ready to run
04 my @jobqueue = $r->zrangebyscore('jobqueue', '-INF', time());
05 for my $job (@jobqueue) {
06 # lock job
07 if($r->set("$job:lock", "$HOSTNAME:$$", 'EX', $TIMEOUT, 'NX')) {
08 # did anyone change it in between? (race condition)
09 my $current_schedule = $r->zscore('jobqueue', $job);
10 if (defined $current_schedule && $current_schedule <= time()) {
11 # all good, we move it now in the job queue to the timeout
12 $r->zadd('jobqueue', time() + $TIMEOUT, $job);
13 return $job;
14 }
15 # unlock job (simple)
16 $r->del("$job:lock");
17 }
18 }
19 return;
20 }