Skip to content
This repository was archived by the owner on Oct 22, 2019. It is now read-only.

Commit 71ecf64

Browse files
committed
Allow passing already configured redis client to the storage adapter
1 parent 43fc3bd commit 71ecf64

2 files changed

Lines changed: 36 additions & 1 deletion

File tree

src/Prometheus/Storage/Redis.php

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,10 @@ public function __construct(array $options = array())
4040
}
4141

4242
$this->options = array_merge(self::$defaultOptions, $options);
43-
$this->redis = new \Redis();
43+
44+
if(isset($this->options['redis']) && $this->options['redis'] instanceof \Redis) {
45+
$this->redis = $this->options['redis'];
46+
}
4447
}
4548

4649
/**
@@ -80,7 +83,13 @@ function (array $metric) {
8083
*/
8184
private function openConnection()
8285
{
86+
if($this->redis != null) {
87+
return;
88+
}
89+
8390
try {
91+
$this->redis = new \Redis();
92+
8493
if ($this->options['persistent_connections']) {
8594
@$this->redis->pconnect($this->options['host'], $this->options['port'], $this->options['timeout']);
8695
} else {

tests/Test/Prometheus/Storage/RedisTest.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,30 @@ public function itShouldThrowAnExceptionOnConnectionFailure()
1717
$redis->flushRedis();
1818
}
1919

20+
public function testReuseRedisClient()
21+
{
22+
$redisClient = $this->getMockBuilder(\Redis::class)->getMock();
23+
$redisStorage = new Redis(['redis' => $redisClient]);
24+
25+
$this->assertAttributeEquals($redisClient, 'redis', $redisStorage);
26+
27+
$redisClient->expects($this->atLeastOnce())
28+
->method('flushAll');
29+
30+
$redisClient->expects($this->never())
31+
->method('connect');
32+
33+
$redisStorage->flushRedis();
34+
}
35+
36+
public function testReuseRedisClientWithDefaultOptions()
37+
{
38+
$redisClient = $this->getMockBuilder(\Redis::class)->getMock();
39+
40+
Redis::setDefaultOptions(['redis' => $redisClient]);
41+
42+
$redisStorage = new Redis();
43+
44+
$this->assertAttributeEquals($redisClient, 'redis', $redisStorage);
45+
}
2046
}

0 commit comments

Comments
 (0)