diff --git a/cluster/cluster.go b/cluster/cluster.go index 6581ce8d..d9bf73a3 100644 --- a/cluster/cluster.go +++ b/cluster/cluster.go @@ -155,6 +155,12 @@ func (cluster *Cluster) Exec(c redis.Connection, cmdLine [][]byte) (result redis return protocol.MakeErrReply("NOAUTH Authentication required") } + if cmdName == "dbsize" { + if ser, ok := cluster.db.(*database2.Server); ok { + return database2.DbSize(c, ser) + } + } + if cmdName == "multi" { if len(cmdLine) != 1 { return protocol.MakeArgNumErrReply(cmdName) diff --git a/commands.md b/commands.md index 1a0d5333..11392696 100644 --- a/commands.md +++ b/commands.md @@ -19,6 +19,7 @@ - keys - bgrewriteaof - copy + - dbsize - String - set - setnx diff --git a/database/server.go b/database/server.go index 12544639..2653c853 100644 --- a/database/server.go +++ b/database/server.go @@ -117,6 +117,9 @@ func (server *Server) Exec(c redis.Connection, cmdLine [][]byte) (result redis.R if cmdName == "info" { return Info(server, cmdLine[1:]) } + if cmdName == "dbsize" { + return DbSize(c, server) + } if cmdName == "slaveof" { if c != nil && c.InMultiState() { return protocol.MakeErrReply("cannot use slave of database within multi") diff --git a/database/systemcmd.go b/database/systemcmd.go index 17735c5b..419428b4 100644 --- a/database/systemcmd.go +++ b/database/systemcmd.go @@ -74,6 +74,11 @@ func isAuthenticated(c redis.Connection) bool { return c.GetPassword() == config.Properties.RequirePass } +func DbSize(c redis.Connection, db *Server) redis.Reply { + keys, _ := db.GetDBSize(c.GetDBIndex()) + return protocol.MakeIntReply(int64(keys)) +} + func GenGodisInfoString(section string, db *Server) []byte { startUpTimeFromNow := getGodisRuninngTime() switch section { diff --git a/database/systemcmd_test.go b/database/systemcmd_test.go index 6fc08427..cf2bd460 100644 --- a/database/systemcmd_test.go +++ b/database/systemcmd_test.go @@ -5,7 +5,9 @@ import ( "github.com/hdt3213/godis/lib/utils" "github.com/hdt3213/godis/redis/connection" "github.com/hdt3213/godis/redis/protocol/asserts" + "math/rand" "testing" + "time" ) func TestPing(t *testing.T) { @@ -59,3 +61,16 @@ func TestInfo(t *testing.T) { ret = testServer.Exec(c, utils.ToCmdLine("INFO", "abc")) asserts.AssertErrReply(t, ret, "Invalid section for 'info' command") } + +func TestDbSize(t *testing.T) { + c := connection.NewFakeConn() + rand.NewSource(time.Now().UnixNano()) + randomNum := rand.Intn(10) + 1 + for i := 0; i < randomNum; i++ { + key := utils.RandString(10) + value := utils.RandString(10) + testServer.Exec(c, utils.ToCmdLine("SET", key, value)) + } + ret := testServer.Exec(c, utils.ToCmdLine("dbsize")) + asserts.AssertIntReply(t, ret, randomNum) +}