RequestCacher.php 1.62 KB
Newer Older
Dominik Hebeler's avatar
Dominik Hebeler committed
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
<?php

namespace App\Console\Commands;

use Cache;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

class RequestCacher extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'requests:cacher';

    const CACHER_QUEUE = 'cacher.queue';
    protected $shouldRun = true;

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Listens to a buffer of fetched search results and writes them to the filesystem cache.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        pcntl_async_signals(true);
        pcntl_signal(SIGINT, [$this, "sig_handler"]);
        pcntl_signal(SIGTERM, [$this, "sig_handler"]);
        pcntl_signal(SIGHUP, [$this, "sig_handler"]);

        while ($this->shouldRun) {
            $cacheItem = Redis::blpop(self::CACHER_QUEUE, 1);
            if (!empty($cacheItem)) {
53
54
55
                $cacheItem = unserialize(base64_decode($cacheItem[1]));
                if (empty($cacheItem["value"])) {
                    $cacheItem["value"] = "no-result";
Dominik Hebeler's avatar
Dominik Hebeler committed
56
                }
57
                Cache::put($cacheItem["key"], $cacheItem["value"], now()->addSeconds($cacheItem["timeSeconds"]));
Dominik Hebeler's avatar
Dominik Hebeler committed
58
59
60
61
62
63
64
65
66
67
            }
        }
    }

    public function sig_handler($sig)
    {
        $this->shouldRun = false;
        echo ("Terminating Cacher Process\n");
    }
}