ZBLOG

how to use gorm to operate redis

To use Redis with Gorm, you need to first import the Redis driver and connect to the Redis server. Here’s an example using the go-redis driver:

  1. Install the go-redis package:
go get github.com/go-redis/redis
  1. Initialize a Redis client in your code:
import "github.com/go-redis/redis"

func main() {
    client := redis.NewClient(&redis.Options{
        Addr:     "localhost:6379",
        Password: "", // no password set
        DB:       0,  // use default DB
    })

    pong, err := client.Ping().Result()
    fmt.Println(pong, err)
}
  1. You can now use Gorm to operate on the Redis database. Note that since Redis is a key-value store, operations in Gorm will be different from those for relational databases.

For example, to insert a new record:

import (
    "github.com/jinzhu/gorm"
    "github.com/go-redis/redis"
)

type User struct {
    ID   uint   `gorm:"primary_key"`
    Name string
    Age  int
}

var db *gorm.DB
var rdb *redis.Client

func init() {
    var err error
    db, err = gorm.Open("mysql", "user:password@tcp(127.0.0.1:3306)/dbname?charset=utf8&parseTime=True&loc=Local")
    if err != nil {
        panic(err)
    }

    rdb = redis.NewClient(&redis.Options{
        Addr:     "localhost:6379",
        Password: "", // no password set
        DB:       0,  // use default DB
    })
}

func main() {
    u := User{Name: "hello", Age: 18}
    b, err := json.Marshal(u)
    if err != nil {
        panic(err)
    }
    err = rdb.Set("user_1", b, 0).Err()
    if err != nil {
        panic(err)
    }
}

To retrieve a record:

b, err := rdb.Get("user_1").Bytes()
if err == redis.Nil {
    fmt.Println("key does not exist")
} else if err != nil {
    panic(err)
} else {
    var u User
    err := json.Unmarshal(b, &u)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%+v\n", u)
}

To update a record:

u.Age = 20
b, err = json.Marshal(u)
if err != nil {
    panic(err)
}
err = rdb.Set("user_1", b, 0).Err()
if err != nil {
    panic(err)
}

To delete a record:

err = rdb.Del("user_1").Err()
if err != nil {
    panic(err)
}

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=1678

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?