Code example:
connect redis:
func InitRedis() *redis.Client {
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
})
return rdb
}
main function:
func pipeline() redis.Pipeliner {
redisclient := redisPkg.InitRedis()
return redisclient.Pipeline()
}
check attempt access
func checkattempt(ctx context.Context, pline redis.Pipeliner) {
now := time.Now()
var (
key = "zaddkey1"
ttl int = 3
)
timeRemove := time.Now().Add((-1) * time.Second * time.Duration(ttl))
formatTime := strconv.FormatInt(timeRemove.UnixNano(), 10)
pline.ZRemRangeByScore(ctx, key, "0", formatTime)
rcmd := pline.ZAdd(ctx, key, &redis.Z{
Score: float64(now.UnixNano()),
Member: now,
})
if err := rcmd.Err(); err != nil {
panic(err)
}
pline.Expire(ctx, key, time.Second*time.Duration(ttl))
pline.ZRangeWithScores(ctx, key, 0, 100)
outputResult, err := pline.Exec(ctx)
if err != nil {
panic(err)
}
count := countExec(outputResult)
fmt.Println("count:", count)
}
counter
func countExec(r []redis.Cmder) int {
var (
countSlice int
)
for _, item := range r {
switch v := item.(type) {
case *redis.ZSliceCmd:
for range v.Val() {
countSlice++
}
}
}
return countSlice
}
full source