|
| 1 | +# golang-sample-with-redis |
| 2 | + |
| 3 | +This repository for practice use redis with golang |
| 4 | + |
| 5 | +## redis hashtable sample |
| 6 | + |
| 7 | +```golang |
| 8 | +package main |
| 9 | + |
| 10 | +import ( |
| 11 | + "context" |
| 12 | + "fmt" |
| 13 | + "log/slog" |
| 14 | + "os" |
| 15 | + |
| 16 | + "github.com/leetcode-golang-classroom/golang-sample-with-redis/internal/config" |
| 17 | + "github.com/leetcode-golang-classroom/golang-sample-with-redis/internal/logger" |
| 18 | + myredis "github.com/leetcode-golang-classroom/golang-sample-with-redis/internal/redis" |
| 19 | + "github.com/leetcode-golang-classroom/golang-sample-with-redis/internal/util" |
| 20 | + "github.com/redis/go-redis/v9" |
| 21 | +) |
| 22 | + |
| 23 | +func main() { |
| 24 | + jsonLogger := slog.New(slog.NewJSONHandler( |
| 25 | + os.Stdout, &slog.HandlerOptions{ |
| 26 | + AddSource: true, |
| 27 | + }, |
| 28 | + )) |
| 29 | + ctx := logger.CtxWithLogger(context.Background(), jsonLogger) |
| 30 | + config.Init(ctx) |
| 31 | + redisURL := config.AppCfg.RedisUrl |
| 32 | + rdb, err := myredis.New(redisURL) |
| 33 | + if err != nil { |
| 34 | + util.FailOnError(ctx, err, fmt.Sprintf("failed to connect to %s\n", redisURL)) |
| 35 | + } |
| 36 | + defer rdb.Close() |
| 37 | + _, err = rdb.Ping(ctx) |
| 38 | + if err != nil { |
| 39 | + util.FailOnError(ctx, err, fmt.Sprintf("failed to ping to %s\n", redisURL)) |
| 40 | + } |
| 41 | + // 建立 struct |
| 42 | + var rh1 = RedisHash{ |
| 43 | + Name: "eddie", |
| 44 | + ID: 123, |
| 45 | + Online: true, |
| 46 | + } |
| 47 | + // 透過 pipeline 方式一次批量設定 hashtable |
| 48 | + rdb.Pipelined(ctx, func(pipe redis.Pipeliner) error { |
| 49 | + pipe.HSet(ctx, "rh1", "name", rh1.Name) |
| 50 | + pipe.HSet(ctx, "rh1", "id", rh1.ID) |
| 51 | + pipe.HSet(ctx, "rh1", "online", rh1.Online) |
| 52 | + return nil |
| 53 | + }) |
| 54 | + var rh2 RedisHash |
| 55 | + // 採用 hash read 的方式一次讀取整個 hashtable 相關的 key 的整個結構 |
| 56 | + err = rdb.HGetAll(ctx, "rh1").Scan(&rh2) |
| 57 | + if err != nil { |
| 58 | + util.FailOnError(ctx, err, "failed on scan rh2") |
| 59 | + } |
| 60 | + jsonLogger.Info("hash sample", slog.Any("rh2", rh2)) |
| 61 | +} |
| 62 | + |
| 63 | +// RedisHash struct for handle |
| 64 | +type RedisHash struct { |
| 65 | + Name string `redis:"name"` |
| 66 | + ID int32 `redis:"id"` |
| 67 | + Online bool `redis:"online"` |
| 68 | +} |
| 69 | + |
| 70 | +``` |
0 commit comments