Skip to content

Commit 754f734

Browse files
authored
Merge pull request #193 from zamzterz/redis-scheme-db-number
Parse the database number from the path of the connection URI.
2 parents 780e15f + 30fbf27 commit 754f734

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

src/main/scala/com/redis/RedisClient.scala

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,14 @@ object RedisClient {
1313
case object SUM extends Aggregate
1414
case object MIN extends Aggregate
1515
case object MAX extends Aggregate
16+
17+
private def extractDatabaseNumber(connectionUri: java.net.URI): Int = {
18+
Option(connectionUri.getPath).map(path =>
19+
if (path.isEmpty) 0
20+
else Integer.parseInt(path.tail)
21+
)
22+
.getOrElse(0)
23+
}
1624
}
1725

1826
trait Redis extends IO with Protocol {
@@ -102,13 +110,14 @@ class RedisClient(override val host: String, override val port: Int,
102110
def this(connectionUri: java.net.URI) = this(
103111
host = connectionUri.getHost,
104112
port = connectionUri.getPort,
113+
database = RedisClient.extractDatabaseNumber(connectionUri),
105114
secret = Option(connectionUri.getUserInfo)
106115
.flatMap(_.split(':') match {
107116
case Array(_, password, _*) Some(password)
108117
case _ None
109118
})
110119
)
111-
override def toString = host + ":" + String.valueOf(port)
120+
override def toString = host + ":" + String.valueOf(port) + "/" + database
112121

113122
def pipeline(f: PipelineClient => Any): Option[List[Any]] = {
114123
send("MULTI")(asString) // flush reply stream
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.redis
2+
3+
import java.net.URI
4+
5+
import org.scalatest.FunSpec
6+
import org.scalatest.Matchers
7+
import org.scalatest.junit.JUnitRunner
8+
import org.junit.runner.RunWith
9+
10+
@RunWith(classOf[JUnitRunner])
11+
class RedisClientSpec extends FunSpec
12+
with Matchers {
13+
14+
describe("constructor") {
15+
it("should parse the db-number from the path of connection uri") {
16+
val client = new RedisClient(new URI("redis://localhost:6379/4"))
17+
client.database shouldBe 4
18+
}
19+
20+
it("should default to db 0 for connection uri without db-number") {
21+
val client = new RedisClient(new URI("redis://localhost:6379"))
22+
client.database shouldBe 0
23+
}
24+
}
25+
26+
describe("toString") {
27+
it("should include the db-number") {
28+
new RedisClient("localhost", 6379, 1).toString shouldBe "localhost:6379/1"
29+
}
30+
}
31+
}

0 commit comments

Comments
 (0)