cache

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2023 License: MulanPSL-2.0 Imports: 9 Imported by: 0

README

Golang本地缓存代码库

变量缓存本地进程内存中,超时释放。

使用

go get gitee.com/ivfzhou/cache@latest
import cache "gitee.com/ivfzhou/cache"

// 创建缓存
c := cache.New()

// 设置缓存
c.Set("key", value, time.Second*10)

// 获取缓存
val, ok := c.Get("key")

// 删除缓存
c.Del("key")

// 设置缓存最大容量
c.SetMaxMemory("256mb")

// 查询缓存是否存在
c.Exists("key")

// 占用内存大小
c.Size()

联系电邮:ivfzhou@aliyun.com

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Get

func Get[T any](c Cache, key string) (t T)

Get 获取缓存,没有缓存或者类型不匹配返回零值。

Types

type Cache

type Cache interface {

	// Set 设置缓存。expire为-1代表永不过期。
	Set(key string, val any, expire time.Duration) bool

	// Get 获取缓存。
	Get(key string) (any, bool)

	// GetDel 获取并删除缓存
	GetDel(key string) (any, bool)

	// Del 删除这个key关联的缓存。
	Del(key string) bool

	// Exists 判断键是否存在与缓存中。
	Exists(key string) bool

	// Size 返回占用内存字节数,
	// 容量仅考虑key和value序列化后的字节大小,不考虑库本身使用的内存占用,也不考虑储存key-value的map的内存对齐占用的内存。
	Size() uint

	// Flush 清除所有键值对。如已有go程在清理则返回false。
	Flush() bool

	// Keys 返回键值对个数。
	Keys() int

	// SetMemoryEvictPolicy 缓存容量超限时的执行策略
	SetMemoryEvictPolicy(MemoryEvictPolicy)

	// SetSerializer 变量序列化策略
	SetSerializer(Serializer)

	// SetLogger 设置log输出对象
	SetLogger(Logger)

	// SetMaxMemory 设置缓存最大大小。默认不限制。
	// 单位:b、kb、mb、gb、tb
	SetMaxMemory(size string) bool
}

func New

func New() Cache

New 创建缓存对象实例。 内部采用json序列化对象储存,而非直接储存引用值。使用标准json库序列化,那么不能json序列化的字段将忽略。 如果设置了最大容量,那么超过容量后将不再进行存储。

type Level

type Level int

Level 日志打印等级

const (
	LevelInfo Level = iota
	LevelWarn
	LevelError
	LevelSilence
)

type Logger

type Logger interface {
	Info(format string, args ...any)
	Warn(format string, args ...any)
	Error(format string, args ...any)
	SetLevel(Level)
}

Logger 日志打印接口

type MemoryEvictPolicy

type MemoryEvictPolicy interface {
	// Handle 当内存已满时调用,返回true表示清理成功
	Handle(Cache) bool
}

MemoryEvictPolicy 缓存容量超限时的执行策略

type Serializer

type Serializer interface {
	Serialize(any) ([]byte, error)
	Deserialize([]byte, any) error
}

Serializer 变量序列化策略

Jump to

Keyboard shortcuts

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