gorm_cache

package module
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 12, 2023 License: MIT Imports: 10 Imported by: 0

README

~~## gorm cache plugin

用于gorm的缓存插件

  • 0侵入业务代码
  • 通过gorm callback实现cache delete以及cache write set
  • 每个模型可以单独配置
  • 默认主键实现key
  • 实现内存以及redis驱动

Quick start

go get github.com/janartist/go-gorm-cache

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"time"

	go_gorm_cache "github.com/janartist/go-gorm-cache"
	"github.com/janartist/go-gorm-cache/store"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

type Product struct {
	gorm.Model
	Code  string
	Price uint
}

// 自定义配置
func (p *Product) GetCacheConf() go_gorm_cache.Conf {
	return go_gorm_cache.Conf{
		EnableWriteSet: true,
		EnableReadSet:  true,
		Ttl:            time.Minute * 10,
	}
}

// 启用(优先级比禁用高)
func (p *Product) IsCacheEnable() bool {
	return true
}

// 禁用
func (p *Product) IsCacheDisable() bool {
	return false
}

func (p *Product) MarshalBinary() (data []byte, err error) {
	return json.Marshal(p)
}

func (p *Product) UnmarshalBinary(data []byte) error {
	return json.Unmarshal(data, p)
}

func main() {
	db, err := gorm.Open(sqlite.Open("file:mockdb?mode=memory&cache=shared&_auto_vacuum=none"), &gorm.Config{})
	if err != nil {
		panic("failed to connect database")
	}

	//opt, err := redis.ParseURL(fmt.Sprintf("redis://:%s@%s/%d", "", "10.1.2.7:6379", 3))
	//if err != nil {
	//	panic(err)
	//}
	//rd := store.NewRedis(redis.NewClient(opt))
	//
	//cache := go_gorm_cache.NewDBCache(rd, go_gorm_cache.DefaultConf)
	//err = db.Use(cache)
	cache := go_gorm_cache.NewDBCache(store.NewMemory(), go_gorm_cache.Conf{})
	err = db.Use(cache)
	if err != nil {
		panic("db.Use connect database")
	}
	db = db.Debug()

	// 迁移 schema
	db.AutoMigrate(&Product{})
	// Create
	db.Create(&Product{Code: "Create", Price: 100})
	// Read
	var product Product
	db.First(&product, 1) // 根据整型主键查找
	fmt.Print("Hit cache Skip Db:", product, "\n")

	//db.First(&product, "code = ?", "D42") // 查找 code 字段值为 D42 的记录

	// Update - 将 product 的 price 更新为 200
	db.Model(&product).Update("Code", "Update")
	fmt.Print("Set Cache", product, "\n")
	// Update - 更新多个字段
	//db.Model(&product).Updates(Product{Price: 200, Code: "F42"}) // 仅更新非零值字段
	//db.Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"})
	var product2 Product
	cache.Get(context.Background(), "products", 1, &product2)
	fmt.Print("Get Cache", product2, "\n")
	// Delete - 删除 product
	db.Delete(&product, 1)
}


Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	DefaultConf = &Conf{
		Prefix:         "gorm_cache",
		EnableReadSet:  false,
		EnableWriteSet: false,
		Ttl:            0,
	}

	// 缓存命中
	CacheHit = fmt.Errorf("cache hit")
	// 缓存跳过
	CacheSkip = fmt.Errorf("cache skip")
)

Functions

This section is empty.

Types

type Conf

type Conf struct {
	Prefix string `json:"prefix" yaml:"prefix"`
	// 开启读库写缓存
	EnableReadSet bool `json:"enable_find_set" yaml:"enable_find_set"`
	// 开启写库写缓存, false为删缓存
	EnableWriteSet bool `json:"enable_create_set" yaml:"enable_create_set"`
	// 默认过期时间
	Ttl time.Duration `json:"ttl" yaml:"ttl"`
}

type ConfigInterface

type ConfigInterface interface {
	GetCacheConf() Conf
}

type DB

type DB struct {
	Conf  Conf
	Store StoreInterface
	// contains filtered or unexported fields
}

func NewDBCache

func NewDBCache(client StoreInterface, conf Conf) *DB

func (*DB) AfterWrite

func (d *DB) AfterWrite(isDel bool) func(*gorm.DB)

增删改后

func (*DB) Before

func (d *DB) Before() func(*gorm.DB)

func (*DB) Get added in v1.0.2

func (d *DB) Get(ctx context.Context, tableName string, id interface{}, dest interface{}) error

func (*DB) Initialize

func (d *DB) Initialize(db *gorm.DB) error

func (*DB) IsEnable

func (d *DB) IsEnable(db *gorm.DB) bool

func (*DB) Name

func (d *DB) Name() string

func (*DB) Query

func (d *DB) Query() func(*gorm.DB)

type DisableInterface

type DisableInterface interface {
	IsCacheDisable() bool
}

type EnableInterface

type EnableInterface interface {
	IsCacheEnable() bool
}

type Group

type Group struct {
	// contains filtered or unexported fields
}

Group represents a class of work and forms a namespace in which units of work can be executed with duplicate suppression.

func (*Group) Do

func (g *Group) Do(key string, fn func() (interface{}, error)) (interface{}, error)

Do executes and returns the results of the given function, making sure that only one execution is in-flight for a given key at a time. If a duplicate comes in, the duplicate caller waits for the original to complete and receives the same results.

type StoreInterface

type StoreInterface interface {
	Del(context.Context, string) error
	Set(context.Context, string, interface{}, time.Duration) error
	Get(context.Context, string, interface{}) error
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL