Redis
 sql >> Database >  >> NoSQL >> Redis

La coda Redis con reclamo scade

Per realizzare una semplice coda in redis che può essere utilizzata per inviare nuovamente i lavori bloccati, proverei qualcosa del genere:

  • 1 elenco "up_for_grabs"
  • 1 elenco "essere_lavorati"
  • blocchi con scadenza automatica

un lavoratore che cerca di ottenere un lavoro farebbe qualcosa del genere:

timeout = 3600
#wrap this in a transaction so our cleanup wont kill the task
#Move the job away from the queue so nobody else tries to claim it
job = RPOPLPUSH(up_for_grabs, being_worked_on)
#Set a lock and expire it, the value tells us when that job will time out. This can be arbitrary though
SETEX('lock:' + job, Time.now + timeout, timeout)
#our application logic
do_work(job)

#Remove the finished item from the queue.
LREM being_worked_on -1 job
#Delete the item's lock. If it crashes here, the expire will take care of it
DEL('lock:' + job)

E ogni tanto, potremmo semplicemente prendere la nostra lista e controllare che tutti i lavori che ci sono in realtà abbiano un lucchetto. Se troviamo dei lavori che NON hanno un lucchetto, significa che è scaduto e il nostro lavoratore probabilmente è andato in crash.In questo caso lo sottoporremmo nuovamente.

Questo sarebbe lo pseudo codice per quello:

loop do
    items = LRANGE(being_worked_on, 0, -1)
    items.each do |job| 
        if !(EXISTS("lock:" + job))
            puts "We found a job that didn't have a lock, resubmitting"
            LREM being_worked_on -1 job
            LPUSH(up_for_grabs, job)
        end
    end
    sleep 60
end