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:
- Install the go-redis package:
go get github.com/go-redis/redis
- 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)
}
- 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)
}