Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

1401: Update leaderbard example to use zrange watch #1402

Merged
merged 2 commits into from
Jan 7, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 30 additions & 28 deletions examples/leaderboard-go/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@ import (
"context"
"encoding/json"
"fmt"
"github.com/dicedb/dicedb-go"
"log"

"github.com/dicedb/dicedb-go"

"math/rand"
"net/http"
"os"
Expand Down Expand Up @@ -65,8 +67,8 @@ func main() {
MaxRetries: 10,
})

go updateScores()
go watchLeaderboard()
go updateScores()

// Serve static files for the frontend
http.Handle("/", http.FileServer(http.Dir(".")))
Expand All @@ -78,48 +80,48 @@ func main() {

func updateScores() {
ctx := context.Background()
key := "match:100"
for {
entry := LeaderboardEntry{
PlayerID: fmt.Sprintf("player:%d", rand.Intn(10)),
Score: rand.Intn(100),
Timestamp: time.Now(),
}
lentry, _ := json.Marshal(entry)
dice.JSONSet(ctx, entry.PlayerID, "$", lentry).Err()
dice.ZAdd(ctx, key, dicedb.Z{
Score: rand.Float64() * 100,
Member: fmt.Sprintf("player:%d", rand.Intn(5)),
})
time.Sleep(2 * time.Second)
}
}

func watchLeaderboard() {
ctx := context.Background()
qwatch := dice.QWatch(ctx)
qwatch.WatchQuery(ctx, `SELECT $key, $value
WHERE $key LIKE 'player:*' AND '$value.score' > 10
ORDER BY $value.score DESC
LIMIT 5;`)
defer qwatch.Close()

ch := qwatch.Channel()
watchConn := dice.WatchConn(ctx)
key := "match:100"
_, err := watchConn.ZRangeWatch(ctx, key, "0", "4", "REV", "WITHSCORES")
if err != nil {
log.Println("failed to create watch connection:", err)
return
}

defer watchConn.Close()

ch := watchConn.Channel()
for {
select {
case msg := <-ch:
entries := toEntries(msg.Updates)
var entries []LeaderboardEntry
for _, dicedbZ := range msg.Data.([]dicedb.Z) {
entry := LeaderboardEntry{
Score: int(dicedbZ.Score),
PlayerID: dicedbZ.Member.(string),
Timestamp: time.Now(),
}
entries = append(entries, entry)
}
broadcast(entries)
case <-ctx.Done():
return
}
}
}

func toEntries(updates []dicedb.KV) []LeaderboardEntry {
var entries []LeaderboardEntry
for _, update := range updates {
var entry LeaderboardEntry
json.Unmarshal([]byte(update.Value.(string)), &entry)
entries = append(entries, entry)
}
return entries
}

func broadcast(entries []LeaderboardEntry) {
cMux.Lock()
defer cMux.Unlock()
Expand Down
Loading