You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
1.1 KiB
Go
53 lines
1.1 KiB
Go
package redis
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
type RankInfo struct {
|
|
OpenId string
|
|
Score int32
|
|
}
|
|
|
|
var client *redis.Client
|
|
|
|
func init() {
|
|
url := "redis://:adhd@123@101.35.201.220:6379/1?protocol=3"
|
|
opts, err := redis.ParseURL(url)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
client = redis.NewClient(opts)
|
|
}
|
|
|
|
func AddScore(appId string, scoreMap map[string]int32) error {
|
|
ctx := context.Background()
|
|
pip := client.Pipeline()
|
|
for openId, score := range scoreMap {
|
|
key := fmt.Sprintf("Score_%s", appId)
|
|
pip.ZIncrBy(ctx, key, float64(score), openId)
|
|
}
|
|
_, err := pip.Exec(ctx)
|
|
return err
|
|
}
|
|
|
|
func GetRank(appId string, topCount int32) ([]*RankInfo, error) {
|
|
ctx := context.Background()
|
|
key := fmt.Sprintf("Score_%s_*", appId)
|
|
cmd := client.ZRevRangeWithScores(ctx, key, 0, int64(topCount))
|
|
result, err := cmd.Result()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
rankList := make([]*RankInfo, 0)
|
|
for _, info := range result {
|
|
rankList = append(rankList, &RankInfo{
|
|
OpenId: info.Member.(string),
|
|
Score: int32(info.Score),
|
|
})
|
|
}
|
|
return rankList, nil
|
|
}
|