gocache

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2021 License: Apache-2.0 Imports: 6 Imported by: 0

README

gocache

Badge Go GoDoc Go Report Card Latest License codecov

支持的功能

1.并发安全;
2.LRU淘汰策略;
3.数据过期,过期策略为懒更新;
4.key和value支持interface;
5.支持返回过期数据和对应error;
6.支持singelfight方式更新下游。

使用示例
func main() {
    cache := gocache.New(gocache.WithExpire(500*time.Second), gocache.WithKeyCnt(10))
    cache.Set(1, 1)
    fmt.Println(cache.Get(1))
}

Documentation

Overview

Package gocache 并发安全、支持lru、支持过期的缓存轮子

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrKeyNotFound key不存在错误
	ErrKeyNotFound = fmt.Errorf("key not found")
	// ErrKeyIsExpired key过期错误
	ErrKeyIsExpired = fmt.Errorf("key is expired")
)

Functions

This section is empty.

Types

type Cache

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

Cache 缓存核心结构

func New

func New(opts ...CacheOptHelper) *Cache

New Cache构造函数

func (*Cache) Get

func (c *Cache) Get(key interface{}) (interface{}, error)

Get 获取数据,返回数据和对应的error。如果数据正常,则error返回nil

func (*Cache) GetAndSet added in v0.0.2

func (c *Cache) GetAndSet(ctx context.Context, key string, fn UpdateCallback) (interface{}, error)

GetAndSet 获取val,若val存在且未过期,则更新至缓存,否则通过singleflight的方式更新至缓存 若更新失败,则使用旧数据兜底并返回对应的error给调用方

func (*Cache) Set

func (c *Cache) Set(key, val interface{}) error

Set 设置数据,设置数据。用error是否为nil来标识是否出错

type CacheOpt

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

CacheOpt Cache参数选项结构

type CacheOptHelper

type CacheOptHelper func(opt *CacheOpt)

CacheOptHelper Cache参数选项结构helper

func WithExpire

func WithExpire(expire time.Duration) CacheOptHelper

WithExpire 设置超时时间

func WithKeyCnt

func WithKeyCnt(keyCnt int) CacheOptHelper

WithKeyCnt 设置Key上限

type UpdateCallback added in v0.0.2

type UpdateCallback func() (interface{}, error)

UpdateCallback 更新数据回调

Jump to

Keyboard shortcuts

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