8000 GitHub - swordkee/gorm-cache: gorm v2的即插即用、无需修改代码的旁路缓存。An easy-to-use look-aside cache solution for gorm v2 users.
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

gorm v2的即插即用、无需修改代码的旁路缓存。An easy-to-use look-aside cache solution for gorm v2 users.

License

Notifications You must be signed in to change notification settings

swordkee/gorm-cache

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

46 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

GoVersion Release Apache-2.0 license

English Version | 中文版本

gorm-cache

gorm-cache aims to provide a look-aside, almost-no-code-modification cache solution for gorm v2 users. It only applys to situations where database table has only one single primary key.

We provide 2 types of cache storage here:

  1. Memory, where all cached data stores in memory of a single server
  2. Redis, where cached data stores in Redis (if you have multiple servers running the same procedure, they don't share the same space in Redis)

Usage

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
}

There're mainly 5 kinds of operations in gorm (gorm function names in brackets):

  1. Query (First/Take/Last/Find/FindInBatches/FirstOrInit/FirstOrCreate/Count/Pluck)
  2. Create (Create/CreateInBatches/Save)
  3. Delete (Delete)
  4. Update (Update/Updates/UpdateColumn/UpdateColumns/Save)
  5. Row (Row/Rows/Scan)

We don't support caching in Row operations.

About

gorm v2的即插即用、无需修改代码的旁路缓存。An easy-to-use look-aside cache solution for gorm v2 users.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Go 99.9%
  • Shell 0.1%
0