Skip to content

Instantly share code, notes, and snippets.

@rueian
Last active May 27, 2022 09:28
Show Gist options
  • Save rueian/129311f2d4c695740e18941dd2f68961 to your computer and use it in GitHub Desktop.
Save rueian/129311f2d4c695740e18941dd2f68961 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"reflect"
"time"
"github.com/rueian/rueidis"
"github.com/rueian/rueidis/om"
)
type MyEntity struct { // define your own entity struct
Key string `json:"key" redis:",key"`
Ver int64 `json:"ver" redis:",ver"`
Val MyValue `json:"val"`
}
type MyValue struct { // nested struct is also supported
Name string `json:"name"`
Time time.Time `json:"time"`
}
func main() {
client, err := rueidis.NewClient(rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6377"}})
if err != nil {
panic(err)
}
defer client.Close()
// initialize a MyEntity repository object infered from generics and backed by RedisJSON module
repo := om.NewJSONRepository("my_entity", MyEntity{}, client)
entity := repo.NewEntity() // initialize a new MyEntity, and
entity.Val.Name = "my_name" // set its fields directly with the help of generics type inference
entity.Val.Time = time.Now().Truncate(time.Nanosecond)
// save the entity to redis
if err = repo.Save(context.Background(), entity); err != nil {
panic(err)
}
// get the entity back with redis server assisted client-side caching
cached, err := repo.FetchCache(context.Background(), entity.Key, time.Second)
if err != nil {
panic(err)
}
fmt.Println(reflect.DeepEqual(entity, cached)) // true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment