cache

package
v1.4.1 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2022 License: MIT Imports: 9 Imported by: 0

README

cache

支持memory缓存和redis缓存。

使用示例


// 实例化缓存类型,根据CType字段选择使用memory或redis
cache := cache.NewUserExampleCache(&model.CacheType{
  CType: "redis",
  Rdb:   c.RedisClient,
})

// -----------------------------------------------------------------------------------------

type userExampleDao struct {
	db    *gorm.DB
	cache cache.UserExampleCache
}

// NewUserExampleDao creating the dao interface
func NewUserExampleDao(db *gorm.DB, cache cache.UserExampleCache) UserExampleDao {
	return &userExampleDao{db: db, cache: cache}
}

// GetByID get a record based on id
func (d *userExampleDao) GetByID(ctx context.Context, id uint64) (*model.UserExample, error) {
	record, err := d.cache.Get(ctx, id)
	if err == nil {
		return record, nil
	}

	if errors.Is(err, model.ErrCacheNotFound) {
		// 从mysql获取
		table := &model.UserExample{}
		err = d.db.WithContext(ctx).Where("id = ?", id).First(table).Error
		if err != nil {
			// if data is empty, set not found cache to prevent cache penetration(防止缓存穿透)
			if errors.Is(err, model.ErrRecordNotFound) {
				err = d.cache.SetCacheWithNotFound(ctx, id)
				if err != nil {
					return nil, err
				}
				return nil, model.ErrRecordNotFound
			}
			return nil, err
		}

		// set cache
		err = d.cache.Set(ctx, id, table, cacheBase.DefaultExpireTime)
		if err != nil {
			return nil, fmt.Errorf("cache.Set error: %v, id=%d", err, id)
		}
		return table, nil
	} else if errors.Is(err, cacheBase.ErrPlaceholder) {
		return nil, model.ErrRecordNotFound
	}

	// fail fast, if cache error return, don't request to db
	return nil, err
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// DefaultExpireTime 默认过期时间
	DefaultExpireTime = time.Hour * 24
	// DefaultNotFoundExpireTime 结果为空时的过期时间 1分钟, 常用于数据为空时的缓存时间(缓存穿透)
	DefaultNotFoundExpireTime = time.Minute
	// NotFoundPlaceholder 占位符
	NotFoundPlaceholder = "*"

	// DefaultClient 生成一个缓存客户端,其中keyPrefix 一般为业务前缀
	DefaultClient Cache

	// ErrPlaceholder .
	ErrPlaceholder = errors.New("cache: placeholder")
	// ErrSetMemoryWithNotFound .
	ErrSetMemoryWithNotFound = errors.New("cache: set memory cache err for not found")
)
View Source
var CacheNotFound = redis.Nil

CacheNotFound no hit cache

Functions

func BuildCacheKey

func BuildCacheKey(keyPrefix string, key string) (string, error)

BuildCacheKey 构建一个带有前缀的缓存key

func Del

func Del(ctx context.Context, keys ...string) error

Del 批量删除

func Get

func Get(ctx context.Context, key string, val interface{}) error

Get 数据

func MultiGet

func MultiGet(ctx context.Context, keys []string, valueMap interface{}) error

MultiGet 批量获取

func MultiSet

func MultiSet(ctx context.Context, valMap map[string]interface{}, expiration time.Duration) error

MultiSet 批量set

func Set

func Set(ctx context.Context, key string, val interface{}, expiration time.Duration) error

Set 数据

func SetCacheWithNotFound

func SetCacheWithNotFound(ctx context.Context, key string) error

SetCacheWithNotFound .

Types

type Cache

type Cache interface {
	Set(ctx context.Context, key string, val interface{}, expiration time.Duration) error
	Get(ctx context.Context, key string, val interface{}) error
	MultiSet(ctx context.Context, valMap map[string]interface{}, expiration time.Duration) error
	MultiGet(ctx context.Context, keys []string, valueMap interface{}) error
	Del(ctx context.Context, keys ...string) error
	SetCacheWithNotFound(ctx context.Context, key string) error
}

Cache 定义cache驱动接口

func NewMemoryCache

func NewMemoryCache(keyPrefix string, encoding encoding.Encoding, newObject func() interface{}) Cache

NewMemoryCache create a memory cache

func NewRedisCache

func NewRedisCache(client *redis.Client, keyPrefix string, encoding encoding.Encoding, newObject func() interface{}) Cache

NewRedisCache new一个cache, client 参数是可传入的,方便进行单元测试

Jump to

Keyboard shortcuts

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