diff --git a/src/Prometheus/Storage/Redis.php b/src/Prometheus/Storage/Redis.php index 04757b2..559ee5f 100644 --- a/src/Prometheus/Storage/Redis.php +++ b/src/Prometheus/Storage/Redis.php @@ -40,7 +40,10 @@ public function __construct(array $options = array()) } $this->options = array_merge(self::$defaultOptions, $options); - $this->redis = new \Redis(); + + if(isset($this->options['redis']) && $this->options['redis'] instanceof \Redis) { + $this->redis = $this->options['redis']; + } } /** @@ -80,7 +83,13 @@ function (array $metric) { */ private function openConnection() { + if($this->redis != null) { + return; + } + try { + $this->redis = new \Redis(); + if ($this->options['persistent_connections']) { @$this->redis->pconnect($this->options['host'], $this->options['port'], $this->options['timeout']); } else { diff --git a/tests/Test/Prometheus/Storage/RedisTest.php b/tests/Test/Prometheus/Storage/RedisTest.php index 8eb1654..90ffc95 100644 --- a/tests/Test/Prometheus/Storage/RedisTest.php +++ b/tests/Test/Prometheus/Storage/RedisTest.php @@ -17,4 +17,30 @@ public function itShouldThrowAnExceptionOnConnectionFailure() $redis->flushRedis(); } + public function testReuseRedisClient() + { + $redisClient = $this->getMockBuilder(\Redis::class)->getMock(); + $redisStorage = new Redis(['redis' => $redisClient]); + + $this->assertAttributeEquals($redisClient, 'redis', $redisStorage); + + $redisClient->expects($this->atLeastOnce()) + ->method('flushAll'); + + $redisClient->expects($this->never()) + ->method('connect'); + + $redisStorage->flushRedis(); + } + + public function testReuseRedisClientWithDefaultOptions() + { + $redisClient = $this->getMockBuilder(\Redis::class)->getMock(); + + Redis::setDefaultOptions(['redis' => $redisClient]); + + $redisStorage = new Redis(); + + $this->assertAttributeEquals($redisClient, 'redis', $redisStorage); + } }