This commit is contained in:
zhaoxiaorong
2025-02-07 13:01:38 +08:00
parent ebcdfe1ee8
commit 57a0d8ae81
52 changed files with 3313 additions and 0 deletions

View File

@@ -0,0 +1,11 @@
github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE=
github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.4 h1:tHnRBy1i5F2Dh8BAFxqFzxKqqvezXrL2OW1TnX+Mlas=
github.com/jinzhu/now v1.1.4/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
gorm.io/driver/mysql v1.3.4 h1:/KoBMgsUHC3bExsekDcmNYaBnfH2WNeFuXqqrqMc98Q=
gorm.io/driver/mysql v1.3.4/go.mod h1:s4Tq0KmD0yhPGHbZEwg1VPlH0vT/GBHJZorPzhcxBUE=
gorm.io/gorm v1.23.4/go.mod h1:l2lP/RyAtc1ynaTjFksBde/O8v9oOGIApu2/xRitmZk=
gorm.io/gorm v1.23.6 h1:KFLdNgri4ExFFGTRGGFWON2P1ZN28+9SJRN8voOoYe0=
gorm.io/gorm v1.23.6/go.mod h1:l2lP/RyAtc1ynaTjFksBde/O8v9oOGIApu2/xRitmZk=

View File

@@ -0,0 +1,92 @@
package main
import (
"context"
"fmt"
"github.com/go-redis/redis/v8"
"github.com/liyuan1125/gorm-cache"
redis2 "github.com/liyuan1125/gorm-cache/store/redis"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"os"
"time"
)
var (
db *gorm.DB
redisClient *redis.Client
cachePlugin *cache.Cache
)
func newDb() {
dsn := "root:123456@tcp(127.0.0.1:3306)/gorm?charset=utf8&parseTime=True&loc=Local"
var err error
db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
fmt.Println(err.Error())
return
}
redisClient = redis.NewClient(&redis.Options{Addr: ":6379"})
cacheConfig := &cache.Config{
Store: redis2.NewWithDb(redisClient), // OR redis2.New(&redis.Options{Addr:"6379"})
Serializer: &cache.DefaultJSONSerializer{},
}
cachePlugin = cache.New(cacheConfig)
if err = db.Use(cachePlugin); err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
}
func basic() {
var username string
ctx := context.Background()
ctx = cache.NewExpiration(ctx, time.Hour)
db.Table("users").WithContext(ctx).Where("id = 1").Limit(1).Pluck("username", &username)
fmt.Println(username)
// output gorm
}
func customKey() {
var nickname string
ctx := context.Background()
ctx = cache.NewExpiration(ctx, time.Hour)
ctx = cache.NewKey(ctx, "nickname")
db.Table("users").WithContext(ctx).Where("id = 1").Limit(1).Pluck("nickname", &nickname)
fmt.Println(nickname)
// output gormwithmysql
}
func useTag() {
var nickname string
ctx := context.Background()
ctx = cache.NewExpiration(ctx, time.Hour)
ctx = cache.NewTag(ctx, "users")
db.Table("users").WithContext(ctx).Where("id = 1").Limit(1).Pluck("nickname", &nickname)
fmt.Println(nickname)
// output gormwithmysql
}
func main() {
newDb()
basic()
customKey()
useTag()
ctx := context.Background()
fmt.Println(redisClient.Keys(ctx, "*").Val())
fmt.Println(cachePlugin.RemoveFromTag(ctx, "users"))
}