gormcache

package module
v0.0.15 Latest Latest
Warning

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

Go to latest
Published: May 2, 2024 License: Apache-2.0 Imports: 13 Imported by: 0

README

gormcache

License GitHub all releases GitHub issues GitHub commit activity Go Report Card GitHub release

gormcache is a fork of the evangwt/grc GORM plugin that provides a way to cache data using BoltDB, redis or memcached at the moment (other backends may be included in the future).

This fork separates the cache backend specifics to their own files in the same gormcache package, and adds the memcached and BoltDB backends.

Features

  • Easy to use: just add gormcache as a GORM plugin and use GORM session options to control the cache behavior.
  • Flexible to customize: you can configure the cache prefix, ttl, and backend client according to your needs.

Installation

Dependencies
go get -u gorm.io/gorm
go get -u github.com/go-redis/redis/v8

, or

go get go.etcd.io/bbolt@latest

, or

go get github.com/bradfitz/gomemcache/memcache

Then you can install gormcache using go get:

go get -u github.com/rgglez/gormcache

Usage

To use gormcache, you need to create a gormcache instance with a BoltDB, redis or memcached client and a cache config, and then add it as a GORM plugin. For example:

package main

import (
        "github.com/rgglez/gormcache"
        "github.com/go-redis/redis/v8"
        "gorm.io/driver/postgres"
        "gorm.io/gorm"
)

func main() {
        // connect to postgres database
        dsn := "host='0.0.0.0' port='5432' user='evan' dbname='cache_test' password='' sslmode=disable TimeZone=Asia/Shanghai"
        db, _ := gorm.Open(postgres.Open(dsn), &gorm.Config{})

	/*
        mdb := memcache.New(fmt.Sprint(cfg["MEMCACHED"].(map[string]interface{})["ENDPOINT"]))

        cache := gormcache.NewGormCache("my_cache", gormcache.NewMemcacheClient(mdb), gormcache.CacheConfig{
                TTL:    600 * time.Second,
                Prefix: "cache:",
        })
	*/

	/*
        bdb, err := bolt.Open("/tmp/cache.db", 0600, nil)
	if err != nil {
		log.Fatalf("could not open db, %v", err)
	}
	defer bdb.Close()
	bdb.Update(func(tx *bolt.Tx) error {
		_, err := tx.CreateBucketIfNotExists([]byte("DB"))
		if err != nil {
			log.Fatalf("could not create root bucket: %v", err)
		}
		return nil
	})
        */

        // connect to redis database
        rdb := redis.NewClient(&redis.Options{
                Addr:     "0.0.0.0:6379",
                Password: "123456",
        })

        // create a gorm cache instance with a redis client and a cache config
        cache := gormcache.NewGormCache("my_cache", gormcache.NewRedisClient(rdb), gormcache.CacheConfig{
                TTL:    60 * time.Second,
                Prefix: "cache:",
        })

        // add the gorm cache instance as a gorm plugin
        if err := db.Use(cache); err != nil {
                log.Fatal(err)
        }

        // now you can use gorm session options to control the cache behavior
}

To enable or disable the cache for a query, you can use the gormcache.UseCacheKey context value with a boolean value. For example:

// use cache with default ttl
db.Session(&gorm.Session{Context: context.WithValue(context.Background(), gormcache.UseCacheKey, true)}).
                Where("id > ?", 10).Find(&users)

// do not use cache
db.Session(&gorm.Session{Context: context.WithValue(context.Background(), gormcache.UseCacheKey, false)}).
                Where("id > ?", 10).Find(&users)

To set a custom ttl for a query, you can use the gormcache.CacheTTLKey context value with a time.Duration value. For example:

// use cache with custom ttl
db.Session(&gorm.Session{Context: context.WithValue(context.WithValue(context.Background(), gormcache.UseCacheKey, true), gormcache.CacheTTLKey, 10*time.Second)}).
                Where("id > ?", 5).Find(&users)

For more examples and details, please refer to the example code.

License

Read the LICENSE file for more information.

This module is based on evangwt/grc.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	UseCacheKey struct{}
	CacheTTLKey struct{}
)

Functions

This section is empty.

Types

type BboltClient added in v0.0.9

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

BboltClient is a wrapper for bbolt client

func NewBboltClient added in v0.0.9

func NewBboltClient(client *bolt.DB) *BboltClient

NewBboltClient returns a new RedisClient instance

func (*BboltClient) Get added in v0.0.9

func (r *BboltClient) Get(ctx context.Context, key string) (interface{}, error)

Get gets value from bbolt by key using json encoding/decoding

func (*BboltClient) Set added in v0.0.9

func (r *BboltClient) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error

Set sets value to bbolt by key with ttl using json encoding/decoding

type CacheClient

type CacheClient interface {
	Get(ctx context.Context, key string) (interface{}, error)
	Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error
}

CacheClient is an interface for cache operations

type CacheConfig

type CacheConfig struct {
	TTL    time.Duration // cache expiration time
	Prefix string        // cache key prefix
}

CacheConfig is a struct for cache options

type GormCache

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

GormCache is a cache plugin for gorm

func NewGormCache

func NewGormCache(name string, client CacheClient, config CacheConfig) *GormCache

NewGormCache returns a new GormCache instance

func (*GormCache) Initialize

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

Initialize initializes the plugin

func (*GormCache) Name

func (g *GormCache) Name() string

Name returns the plugin name

type MemcacheClient

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

MemcacheClient is a wrapper for gomemcache client

func NewMemcacheClient

func NewMemcacheClient(client *memcache.Client) *MemcacheClient

NewMemcacheClient returns a new RedisClient instance

func (*MemcacheClient) Get

func (r *MemcacheClient) Get(ctx context.Context, key string) (interface{}, error)

Get gets value from memcache by key using json encoding/decoding

func (*MemcacheClient) Set

func (r *MemcacheClient) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error

Set sets value to memcache by key with ttl using json encoding/decoding

type RedisClient

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

RedisClient is a wrapper for go-redis client

func NewRedisClient

func NewRedisClient(client *redis.Client) *RedisClient

NewRedisClient returns a new RedisClient instance

func (*RedisClient) Get

func (r *RedisClient) Get(ctx context.Context, key string) (interface{}, error)

Get gets value from redis by key using json encoding/decoding

func (*RedisClient) Set

func (r *RedisClient) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error

Set sets value to redis by key with ttl using json encoding/decoding

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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