1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the PHPProm package. |
5
|
|
|
* |
6
|
|
|
* (c) Philip Lehmann-Böhm <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace PHPProm\Storage; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Class Memcached |
16
|
|
|
* Storage implementation using memcached. |
17
|
|
|
* @package PHPProm\Storage |
18
|
|
|
*/ |
19
|
|
|
class Memcached extends AbstractStorage { |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var \Memcached |
23
|
|
|
* The memcached connection. |
24
|
|
|
*/ |
25
|
|
|
protected $memcached; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @var string |
29
|
|
|
* The global key prefix. |
30
|
|
|
*/ |
31
|
|
|
protected $prefix; |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Memcached constructor. |
35
|
|
|
* |
36
|
|
|
* @param string $host |
37
|
|
|
* the connection host |
38
|
|
|
* @param int $port |
39
|
|
|
* the connection port, default 11211 |
40
|
|
|
* @param string $prefix |
41
|
|
|
* the global key prefix to use, default 'PHPProm:' |
42
|
|
|
*/ |
43
|
|
|
public function __construct($host, $port = 11211, $prefix = 'PHPProm:') { |
44
|
|
|
parent::__construct(); |
45
|
|
|
$this->memcached = new \Memcached(); |
46
|
|
|
$this->memcached->addServer($host, $port); |
47
|
|
|
$this->prefix = $prefix; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* {@inheritdoc} |
52
|
|
|
*/ |
53
|
|
|
public function storeMeasurement($metric, $key, $value) { |
54
|
|
|
$this->memcached->set($this->prefix.$metric.':'.$key, $value); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* {@inheritdoc} |
59
|
|
|
*/ |
60
|
|
|
public function incrementMeasurement($metric, $key) { |
61
|
|
|
// Increment doesn't work on older versions, see |
62
|
|
|
// https://github.com/php-memcached-dev/php-memcached/issues/133 |
63
|
|
|
$value = $this->memcached->get($this->prefix.$metric.':'.$key); |
64
|
|
|
if ($value === false) { |
65
|
|
|
$value = 0; |
66
|
|
|
} |
67
|
|
|
$value++; |
68
|
|
|
$this->storeMeasurement($metric, $key, $value); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* {@inheritdoc} |
73
|
|
|
*/ |
74
|
|
|
public function getMeasurements($metric, array $keys, $defaultValue = 'Nan') { |
75
|
|
|
$measurements = []; |
76
|
|
|
foreach ($keys as $key) { |
77
|
|
|
$measurements[$key] = $defaultValue; |
78
|
|
|
} |
79
|
|
|
$prefixedKeys = array_map(function($key) use ($metric) { |
80
|
|
|
return $this->prefix.$metric.':'.$key; |
81
|
|
|
}, $keys); |
82
|
|
|
foreach ($this->memcached->getMulti($prefixedKeys) as $key => $value) { |
83
|
|
|
$unprefixedKey = substr($key, strlen($this->prefix) + strlen($metric) + 1); |
84
|
|
|
$measurements[$unprefixedKey] = $value !== false ? (float)$value : $defaultValue; |
85
|
|
|
} |
86
|
|
|
return $measurements; |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|