Skip to content

Commit

Permalink
Add randomkey command
Browse files Browse the repository at this point in the history
  • Loading branch information
NaNShaner authored and HDT3213 committed Apr 10, 2023
1 parent d0a7a21 commit 6103ca0
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 0 deletions.
1 change: 1 addition & 0 deletions cluster/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ func makeRouter() map[string]CmdFunc {
routerMap["incrbyfloat"] = defaultFunc
routerMap["decr"] = defaultFunc
routerMap["decrby"] = defaultFunc
routerMap["randomkey"] = randomkey

routerMap["lpush"] = defaultFunc
routerMap["lpushx"] = defaultFunc
Expand Down
4 changes: 4 additions & 0 deletions cluster/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ func info(cluster *Cluster, c redis.Connection, cmdLine CmdLine) redis.Reply {
return cluster.db.Exec(c, cmdLine)
}

func randomkey(cluster *Cluster, c redis.Connection, cmdLine CmdLine) redis.Reply {
return cluster.db.Exec(c, cmdLine)
}

/*----- utils -------*/

func makeArgs(cmd string, args ...string) [][]byte {
Expand Down
11 changes: 11 additions & 0 deletions database/string.go
Original file line number Diff line number Diff line change
Expand Up @@ -827,6 +827,16 @@ func execBitPos(db *DB, args [][]byte) redis.Reply {
return protocol.MakeIntReply(offset)
}

// GetRandomKey Randomly return (do not delete) a key from the godis
func getRandomKey(db *DB, args [][]byte) redis.Reply {
k := db.data.RandomKeys(1)
if len(k) == 0 {
return &protocol.NullBulkReply{}
}
var key []byte
return protocol.MakeBulkReply(strconv.AppendQuote(key, k[0]))
}

func init() {
RegisterCommand("Set", execSet, writeFirstKey, rollbackFirstKey, -3, flagWrite)
RegisterCommand("SetNx", execSetNX, writeFirstKey, rollbackFirstKey, 3, flagWrite)
Expand All @@ -852,5 +862,6 @@ func init() {
RegisterCommand("GetBit", execGetBit, readFirstKey, nil, 3, flagReadOnly)
RegisterCommand("BitCount", execBitCount, readFirstKey, nil, -2, flagReadOnly)
RegisterCommand("BitPos", execBitPos, readFirstKey, nil, -3, flagReadOnly)
RegisterCommand("Randomkey", getRandomKey, readAllKeys, nil, 1, flagReadOnly)

}
10 changes: 10 additions & 0 deletions database/string_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -802,3 +802,13 @@ func TestBitPos(t *testing.T) {
actual = testDB.Exec(nil, utils.ToCmdLine("BitPos", key, "-1"))
asserts.AssertErrReply(t, actual, "ERR bit is not an integer or out of range")
}

func TestRandomkey(t *testing.T) {
testDB.Flush()
for i := 0; i < 10; i++ {
key := utils.RandString(10)
testDB.Exec(nil, utils.ToCmdLine2("SET", key, key))
}
actual := testDB.Exec(nil, utils.ToCmdLine("Randomkey"))
asserts.AssertNotError(t, actual)
}

0 comments on commit 6103ca0

Please sign in to comment.