AdSense

網頁

2023/1/20

Golang 存取Redis

Go存取Redis的方式如下。


範例環境:


Go可使用go-redis套件來存取Redis server。


事前要求

參考「Docker 安裝並運行Redis」在Docker安裝Redis server。


安裝go-redis

在Go專案根目錄以命令列輸入go get github.com/go-redis/redis/v9安裝(Redis版本7)

~/../go-demo% go get github.com/go-redis/redis/v9
go: downloading github.com/go-redis/redis v6.15.9+incompatible
go: downloading github.com/go-redis/redis/v9 v9.0.0-rc.2
go: downloading github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f
go: downloading github.com/cespare/xxhash/v2 v2.1.2
go: added github.com/cespare/xxhash/v2 v2.1.2
go: added github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f
go: added github.com/go-redis/redis/v9 v9.0.0-rc.2


使用

呼叫redis.NewClient建立redis.Client來存取redis server,建立時傳入參數redis.Options設定redis位址及密碼。

呼叫redis.Client.Set設定key及對應的值。

呼叫redis.Client.Get以key取得對應的值。

main.go

package main

import (
    "context"
    "fmt"

    "github.com/go-redis/redis/v9"
)

func main() {
    ctx := context.Background()

    rdb := NewRedisClient()
    err := rdb.Set(ctx, "name", "John", 0).Err()
    if err != nil {
        panic(err)
    }

    val, err := rdb.Get(ctx, "name").Result()
    if err != nil {
        panic(err)
    }
    fmt.Println(val) // John
}

func NewRedisClient() *redis.Client {
    return redis.NewClient(&redis.Options{
        Addr:     "localhost:6379",
        Password: "12345",
        DB:       0, // use default DB
    })
}

github


沒有留言:

AdSense