gormcache

package module
v1.23.1 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2022 License: MIT Imports: 7 Imported by: 1

README

gorm-cache

Go

Overview

gormcache is cache plugin for gorm.io/gorm.

gormcache uses sql statement as key, sql result as value.

It sets cache and auto expires cache after the specified duration.

It can't delete or update the cache when sql do deleting or updating.

Quick Start

package main

import (
	"context"
	"database/sql"
	"time"

	"github.com/go-redis/redis/v8"
	gormcache "github.com/woorui/gorm-cache"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

type User struct {
	gorm.Model
	Name   string `gorm:"type:text;not null;"`
	Gender uint   `gorm:"type:int8;not null;"`
}

type Rdb struct {
	client *redis.Client
}

func RedisKV(client *redis.Client) gormcache.CacheKV { return &Rdb{client: client} }

func (r *Rdb) Get(ctx context.Context, key string) (bool, string, error) {
	val, err := r.client.Get(ctx, key).Result()
	if err != nil && err != redis.Nil {
		return false, "", err
	}
	return err == redis.Nil, val, nil
}

func (r *Rdb) Set(ctx context.Context, key, value string, exp time.Duration) error {
	return r.client.SetEX(ctx, key, value, exp).Err()
}

func main() {
	sqlDB, err := sql.Open("postgres", "postgres://admin:123456@127.0.0.1:5432/user")
	if err != nil {
		panic(err)
	}
	db, err := gorm.Open(postgres.New(postgres.Config{Conn: sqlDB}))
	if err != nil {
		panic(err)
	}

	rdb := redis.NewClient(&redis.Options{Addr: "127.0.0.1:6379"})

	db.Use(gormcache.GormCache(RedisKV(rdb), 5*time.Second, gormcache.Models()))

	if err := db.Model(&User{}).Create(&User{Name: "Mike", Gender: 1}).Error; err != nil {
		panic(err)
	}

	// cached.
	user := &User{}
	if err := db.Model(&User{}).First(user).Where("name=?", "Mike"); err != nil {
		panic(err)
	}

	// cached.
	users := []User{}
	if err := db.Model(&User{}).Find(&users).Where("gender=?", 1); err != nil {
		panic(err)
	}
}

Documentation

Overview

gorm-cache

## Overview

gormcache is cache plugin for gorm.io/gorm.

gormcache uses sql statement as key, sql result as value.

It sets cache and auto expires cache after the specified duration.

It can't delete or update the cache when sql do deleting or updating.

## Quick Start

```go package main

import (

"context"
"database/sql"
"time"

"github.com/go-redis/redis/v8"
gormcache "github.com/woorui/gorm-cache"
"gorm.io/driver/postgres"
"gorm.io/gorm"

)

type User struct {
	gorm.Model
	Name   string `gorm:"type:text;not null;"`
	Gender uint   `gorm:"type:int8;not null;"`
}
type Rdb struct {
	client *redis.Client
}

func RedisKV(client *redis.Client) gormcache.CacheKV { return &Rdb{client: client} }

func (r *Rdb) Get(ctx context.Context, key string) (bool, string, error) {
	val, err := r.client.Get(ctx, key).Result()
	if err != nil && err != redis.Nil {
		return false, "", err
	}
	return err == redis.Nil, val, nil
}
func (r *Rdb) Set(ctx context.Context, key, value string, exp time.Duration) error {
	return r.client.SetEX(ctx, key, value, exp).Err()
}
func main() {
	sqlDB, err := sql.Open("postgres", "postgres://admin:123456@127.0.0.1:5432/user")
	if err != nil {
		panic(err)
	}
	db, err := gorm.Open(postgres.New(postgres.Config{Conn: sqlDB}))
	if err != nil {
		panic(err)
	}

	rdb := redis.NewClient(&redis.Options{Addr: "127.0.0.1:6379"})

	db.Use(gormcache.GormCache(RedisKV(rdb), 5*time.Second, gormcache.Models()))

	if err := db.Model(&User{}).Create(&User{Name: "Mike", Gender: 1}).Error; err != nil {
		panic(err)
	}

	// cached.
	user := &User{}
	if err := db.Model(&User{}).First(user).Where("name=?", "Mike"); err != nil {
		panic(err)
	}

	// cached.
	users := []User{}
	if err := db.Model(&User{}).Find(&users).Where("gender=?", 1); err != nil {
		panic(err)
	}
}

```

Index

Constants

This section is empty.

Variables

View Source
var Name = "gorm-cache"

Functions

func NewErrGormCache

func NewErrGormCache(err error) error

NewErrGormCache return ErrGormCache.

Types

type CacheKV

type CacheKV interface {
	Get(ctx context.Context, key string) (bool, string, error)
	Set(ctx context.Context, key, value string, exp time.Duration) error
}

CacheKV cache the sql result.

type ErrGormCache

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

ErrGormCache error for gorm-cache.

func (*ErrGormCache) Error

func (e *ErrGormCache) Error() string

type GormCacher

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

GormCacher is cache plugin for gorm.io/gorm.

func GormCache

func GormCache(kv CacheKV, exp time.Duration, options ...Option) *GormCacher

GormCache implements `gorm.Plugin` interface, exp is auto expires cache duration, Models is gorm model to be cached.

func (*GormCacher) Initialize

func (g *GormCacher) Initialize(db *gorm.DB) error

Initialize `gorm.Plugin` implements.

func (*GormCacher) Name

func (g *GormCacher) Name() string

Name `gorm.Plugin` implements.

type Marshaler added in v1.23.1

type Marshaler interface {
	Marshal(interface{}) ([]byte, error)
	Unmarshal(data []byte, v interface{}) error
}

Marshaler defines how to set to cache.

the default Marshaler is std json.Marshal and json.Unmarshal.

type Option

type Option func(*GormCacher)

func CacheKeyFunc

func CacheKeyFunc(f func(*gorm.DB) string) Option

CacheKeyFunc allow you diy cache key for CacheKV.

func Models

func Models(models ...interface{}) Option

Models accept model that you want to be cached.

func OptMarshaler added in v1.23.1

func OptMarshaler(marshaler Marshaler) Option

OptMarshaler inject your Marshaler.

Directories

Path Synopsis
cachekv module

Jump to

Keyboard shortcuts

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