/
Redis.php
84 lines (73 loc) · 2.17 KB
/
Redis.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
83
84
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\Cache\Backend;
/**
* Redis wrapper to extend current implementation behaviour.
*/
class Redis extends \Cm_Cache_Backend_Redis
{
/**
* Local state of preloaded keys.
*
* @var array
*/
private $preloadedData = [];
/**
* Array of keys to be preloaded.
*
* @var array
*/
private $preloadKeys = [];
/**
* @param array $options
*/
public function __construct($options = array())
{
$this->preloadKeys = $options['preload_keys'] ?? [];
parent::__construct($options);
}
/**
* Load value with given id from cache
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @return bool|string
*/
public function load($id, $doNotTestCacheValidity = false)
{
if (!empty($this->preloadKeys) && empty($this->preloadedData)) {
$redis = $this->_slave ?? $this->_redis;
$redis = $redis->pipeline();
foreach ($this->preloadKeys as $key) {
$redis->hGet(self::PREFIX_KEY . $key, self::FIELD_DATA);
}
$this->preloadedData= array_combine($this->preloadKeys, $redis->exec());
}
if (isset($this->preloadedData[$id])) {
return $this->_decodeData($this->preloadedData[$id]);
}
return parent::load($id, $doNotTestCacheValidity = false);
}
/**
* The idea is that base implementation doesn't handle errors on save operations.
* Which may occurs when Redis cannot evict keys, which is expected in some cases.
*
* @param string $data
* @param string $id
* @param array $tags
* @param bool $specificLifetime
* @return bool
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
try {
parent::save($data, $id, $tags, $specificLifetime);
} catch (\Throwable $exception) {
return false;
}
return true;
}
}