From 71ecf6461991ae9cb11628d6fbab4ffb3a6f03c1 Mon Sep 17 00:00:00 2001 From: Boris Dudelsack Date: Thu, 15 Sep 2016 08:29:29 +0200 Subject: [PATCH] Allow passing already configured redis client to the storage adapter --- src/Prometheus/Storage/Redis.php | 11 ++++++++- tests/Test/Prometheus/Storage/RedisTest.php | 26 +++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) 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); + } }