# README
gorm-cache
旨在为gorm v2用户提供一个即插即用的旁路缓存解决方案。本缓存只适用于数据库表单主键时的场景。
我们提供2种存储介质:
- 内存 (所有数据存储在单服务器的内存中)
- Redis (所有数据存储在redis中,如果你有多个实例使用本缓存,那么他们不共享redis存储空间)
使用说明
package main
import (
"context"
"github.com/redis/go-redis/v9"
"github.com/swordkee/gorm-cache/cache"
"github.com/swordkee/gorm-cache/config"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func main() {
dsn := "user:pass@tcp(127.0.0.1:3306)/database_name?charset=utf8mb4"
db, _ := gorm.Open(mysql.Open(dsn), &gorm.Config{})
redisClient := redis.NewUniversalClient(&redis.UniversalOptions{
Addrs: []string{"localhost:6379"},
})
// More options in `config.config.go`
db.Use(cache.NewPlugin(cache.WithRedisConfig(redisClient))) // use gorm plugin
// cache.AttachToDB(db)
var users []User
ctx := context.Background()
db.WithContext(ctx).Where("value > ?", 123).Find(&users) // search cache not hit, objects cached
db.WithContext(ctx).Where("value > ?", 123).Find(&users) // search cache hit
db.WithContext(ctx).Where("id IN (?)", []int{1, 2, 3}).Find(&users) // primary key cache not hit, users cached
db.WithContext(ctx).Where("id IN (?)", []int{1, 3}).Find(&users) // primary key cache hit
}
在gorm中主要有5种操作(括号中是gorm中对应函数名):
- Query (First/Take/Last/Find/FindInBatches/FirstOrInit/FirstOrCreate/Count/Pluck)
- Create (Create/CreateInBatches/Save)
- Delete (Delete)
- Update (Update/Updates/UpdateColumn/UpdateColumns/Save)
- Row (Row/Rows/Scan)
我们不支持Row操作的缓存。
# Packages
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author