gcache

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2025 License: MIT Imports: 21 Imported by: 0

README

GMC Cache 模块

简介

GMC Cache 模块提供统一的缓存接口,支持多种缓存后端,包括 Redis、内存缓存和文件缓存。支持多数据源配置和管理。

功能特性

  • 多种缓存后端:支持 Redis、Memory、File 三种缓存类型
  • 多数据源支持:可同时配置和使用多个缓存实例
  • 统一接口:提供统一的缓存操作 API
  • 键前缀:支持为每个缓存设置键前缀
  • 连接池:Redis 缓存支持连接池配置
  • 自动过期:支持键的自动过期
  • 调试模式:支持调试日志输出

安装

go get github.com/snail007/gmc/module/cache

快速开始

基本使用
package main

import (
    "fmt"
    "time"
    "github.com/snail007/gmc"
)

func main() {
    // 加载配置
    cfg := gmc.New.Config()
    cfg.SetConfigFile("app.toml")
    err := cfg.ReadInConfig()
    if err != nil {
        panic(err)
    }
    
    // 初始化缓存
    err = gmc.Cache.Init(cfg)
    if err != nil {
        panic(err)
    }
    
    // 获取默认缓存实例
    cache := gmc.Cache.Cache()
    
    // 设置键值(5 秒过期)
    err = cache.Set("key", "value", 5*time.Second)
    if err != nil {
        panic(err)
    }
    
    // 获取值
    value, err := cache.Get("key")
    if err != nil {
        panic(err)
    }
    fmt.Println("Value:", value)
    
    // 删除键
    err = cache.Del("key")
    if err != nil {
        panic(err)
    }
}
使用多个缓存实例
package main

import (
    "github.com/snail007/gmc"
    "time"
)

func main() {
    cfg := gmc.New.Config()
    cfg.SetConfigFile("app.toml")
    cfg.ReadInConfig()
    gmc.Cache.Init(cfg)
    
    // 使用默认缓存
    defaultCache := gmc.Cache.Cache()
    defaultCache.Set("key1", "value1", time.Minute)
    
    // 使用指定 ID 的缓存
    sessionCache := gmc.Cache.Cache("session")
    sessionCache.Set("session_id", "user123", time.Hour)
    
    // 使用不同类型的缓存
    redisCache := gmc.Cache.Redis("redis1")
    memoryCache := gmc.Cache.Memory("mem1")
    fileCache := gmc.Cache.File("file1")
}
Redis 缓存
package main

import (
    "fmt"
    "time"
    "github.com/snail007/gmc/module/cache"
)

func main() {
    // 创建 Redis 缓存配置
    cfg := &gcache.RedisCacheConfig{
        Addr:            "127.0.0.1:6379",
        Password:        "",
        DBNum:           0,
        Prefix:          "myapp:",
        MaxIdle:         10,
        MaxActive:       30,
        IdleTimeout:     300 * time.Second,
        MaxConnLifetime: 3600 * time.Second,
        Wait:            true,
        Timeout:         10 * time.Second,
        Debug:           false,
    }
    
    // 创建 Redis 缓存实例
    cache := gcache.NewRedisCache(cfg)
    
    // 使用缓存
    cache.Set("user:1", "Alice", time.Hour)
    value, _ := cache.Get("user:1")
    fmt.Println(value)
}
内存缓存
package main

import (
    "time"
    "github.com/snail007/gmc/module/cache"
)

func main() {
    // 创建内存缓存配置
    cfg := &gcache.MemCacheConfig{
        CleanupInterval: 10 * time.Minute,
    }
    
    // 创建内存缓存实例
    cache := gcache.NewMemCache(cfg)
    
    // 使用缓存
    cache.Set("temp", "data", 5*time.Minute)
    value, _ := cache.Get("temp")
}
文件缓存
package main

import (
    "time"
    "github.com/snail007/gmc/module/cache"
)

func main() {
    // 创建文件缓存配置
    cfg := &gcache.FileCacheConfig{
        Dir:             "./cache",
        CleanupInterval: 10 * time.Minute,
    }
    
    // 创建文件缓存实例
    cache, err := gcache.NewFileCache(cfg)
    if err != nil {
        panic(err)
    }
    
    // 使用缓存
    cache.Set("file_key", "content", time.Hour)
    value, _ := cache.Get("file_key")
}

配置文件

完整配置示例
[cache]
# 默认缓存 ID
default = "default"

# Redis 缓存配置
[[cache.redis]]
enable = true
id = "default"
address = "127.0.0.1:6379"
password = ""
dbnum = 0
prefix = "myapp:"
# 超时时间(秒)
timeout = 10
# 最大空闲连接数
maxidle = 10
# 最大活动连接数
maxactive = 30
# 空闲连接超时(秒)
idletimeout = 300
# 连接最大生命周期(秒)
maxconnlifetime = 3600
# 是否等待可用连接
wait = true
# 调试模式
debug = false

# 会话缓存(Redis)
[[cache.redis]]
enable = true
id = "session"
address = "127.0.0.1:6379"
password = ""
dbnum = 1
prefix = "sess:"
timeout = 10
maxidle = 5
maxactive = 20

# 内存缓存配置
[[cache.memory]]
enable = true
id = "mem1"
# 清理过期键的间隔(秒)
cleanupinterval = 600

# 文件缓存配置
[[cache.file]]
enable = true
id = "file1"
# 缓存文件存储目录
dir = "./cache"
# 清理过期文件的间隔(秒)
cleanupinterval = 600

API 参考

全局函数
// 初始化缓存系统
func Init(cfg gcore.Config) error

// 获取默认缓存或指定 ID 的缓存
func Cache(id ...string) gcore.Cache

// 获取 Redis 缓存
func Redis(id ...string) gcore.Cache

// 获取内存缓存
func Memory(id ...string) gcore.Cache

// 获取文件缓存
func File(id ...string) gcore.Cache

// 设置日志记录器
func SetLogger(logger gcore.Logger)
Cache 接口
type Cache interface {
    // 设置键值
    Set(key string, value interface{}, ttl time.Duration) error
    
    // 获取值
    Get(key string) (interface{}, error)
    
    // 删除键
    Del(key string) error
    
    // 检查键是否存在
    Exists(key string) (bool, error)
    
    // 设置过期时间
    Expire(key string, ttl time.Duration) error
    
    // 增加数值
    Incr(key string, delta int64) (int64, error)
    
    // 减少数值
    Decr(key string, delta int64) (int64, error)
    
    // 获取多个键的值
    MGet(keys ...string) ([]interface{}, error)
    
    // 设置多个键值
    MSet(items map[string]interface{}, ttl time.Duration) error
    
    // 关闭缓存连接
    Close() error
}
配置结构
RedisCacheConfig
type RedisCacheConfig struct {
    Debug           bool
    Prefix          string
    Logger          gcore.Logger
    Addr            string
    Password        string
    DBNum           int
    MaxIdle         int
    MaxActive       int
    IdleTimeout     time.Duration
    Wait            bool
    MaxConnLifetime time.Duration
    Timeout         time.Duration
}
MemCacheConfig
type MemCacheConfig struct {
    CleanupInterval time.Duration
}
FileCacheConfig
type FileCacheConfig struct {
    Dir             string
    CleanupInterval time.Duration
}

使用场景

  1. 会话存储:存储用户会话数据
  2. 页面缓存:缓存渲染后的 HTML 页面
  3. API 响应缓存:缓存 API 查询结果
  4. 数据库查询缓存:缓存频繁查询的数据
  5. 限流计数:使用 Incr/Decr 实现限流
  6. 临时数据存储:存储临时文件上传信息

最佳实践

1. 使用键前缀
// 为不同模块使用不同前缀,避免键冲突
cfg := &gcache.RedisCacheConfig{
    Prefix: "user:",
    // ...
}
2. 设置合理的过期时间
// 根据数据特性设置过期时间
cache.Set("hot_data", value, 5*time.Minute)    // 热数据
cache.Set("cold_data", value, 1*time.Hour)     // 冷数据
cache.Set("static_data", value, 24*time.Hour)  // 静态数据
3. 错误处理
value, err := cache.Get("key")
if err != nil {
    if err.Error() == "key not found" {
        // 键不存在,从数据库加载
        value = loadFromDatabase()
        cache.Set("key", value, time.Hour)
    } else {
        // 其他错误
        log.Printf("Cache error: %v", err)
    }
}
4. 批量操作
// 使用 MSet 批量设置,提高性能
items := map[string]interface{}{
    "key1": "value1",
    "key2": "value2",
    "key3": "value3",
}
cache.MSet(items, time.Hour)

// 使用 MGet 批量获取
values, err := cache.MGet("key1", "key2", "key3")

性能考虑

  1. 连接池配置:合理设置 MaxIdle 和 MaxActive
  2. 键前缀长度:前缀不要过长,影响性能
  3. 值大小:避免缓存过大的对象
  4. 过期时间:合理设置过期时间,避免内存浪费
  5. 清理间隔:内存和文件缓存的清理间隔影响性能

注意事项

  1. Redis 连接:确保 Redis 服务可访问
  2. 文件权限:文件缓存需要对目录有写权限
  3. 内存限制:内存缓存受进程内存限制
  4. 并发安全:所有缓存实现都是并发安全的
  5. 序列化:复杂对象会被序列化存储

相关链接

Documentation

Index

Constants

View Source
const (
	// NoExpiration for use with functions that take an expiration time.
	NoExpiration time.Duration = -1
	// DefaultExpiration for use with functions that take an expiration time. Equivalent to
	// passing in the same expiration duration as was given to New() or
	// NewFrom() when the cache was created (e.g. 5 minutes.)
	DefaultExpiration time.Duration = 0
)

Variables

View Source
var (
	// ErrKeyNotExists is the error of key not exists
	ErrKeyNotExists = fmt.Errorf("key not exists")
)

Functions

func AddCacheU

func AddCacheU(id string, c gcore.Cache)

func Cache

func Cache(id ...string) gcore.Cache

func CacheU

func CacheU(id ...string) gcore.Cache

func Exists

func Exists(path string) bool

func Init

func Init(cfg0 gcore.Config) (err error)

Init parse app.toml database configuration, `cfg` is Config object of app.toml

func SetLogger

func SetLogger(l gcore.Logger)

Types

type FileCache

type FileCache struct {
	gcore.Cache
	// contains filtered or unexported fields
}

FileCache represents a file cache adapter implementation.

func File

func File(id ...string) *FileCache

File acquires a file cache object associated the id, id default is : `default`

func NewFileCache

func NewFileCache(cfg interface{}) (cache *FileCache, err error)

NewFileCache creates and returns a new file cache.

func (*FileCache) Clear

func (c *FileCache) Clear() error

Clear deletes all cached data.

func (*FileCache) Decr

func (c *FileCache) Decr(key string) (int64, error)

Decr decrease cached int value.

func (*FileCache) DecrN

func (c *FileCache) DecrN(key string, n int64) (val int64, err error)

DecrN decrease value N by key

func (*FileCache) Del

func (c *FileCache) Del(key string) error

Del deletes cached value by given key.

func (*FileCache) DelMulti

func (c *FileCache) DelMulti(keys []string) (err error)

func (*FileCache) Get

func (c *FileCache) Get(key string) (val string, err error)

Get gets cached value by given key.

func (*FileCache) GetMulti

func (c *FileCache) GetMulti(keys []string) (map[string]string, error)

GetMulti get multiple keys values.

func (*FileCache) Has

func (c *FileCache) Has(key string) (bool, error)

Has returns true if cached value exists.

func (*FileCache) Incr

func (c *FileCache) Incr(key string) (int64, error)

Incr increases cached int-type value by given key as a counter.

func (*FileCache) IncrN

func (c *FileCache) IncrN(key string, n int64) (val int64, err error)

IncrN increase value N by key

func (*FileCache) Set

func (c *FileCache) Set(key string, val string, ttl time.Duration) error

Set sets value into cache with key and expire time. If expired is 0, it will be deleted by next GC operation.

func (*FileCache) SetMulti

func (c *FileCache) SetMulti(values map[string]string, ttl time.Duration) (err error)

func (*FileCache) String

func (c *FileCache) String() string

type FileCacheConfig

type FileCacheConfig struct {
	Dir             string
	CleanupInterval time.Duration
}

func NewFileCacheConfig

func NewFileCacheConfig() *FileCacheConfig

type Item

type Item struct {
	Val     string
	Created int64
	TTL     int64
}

Item represents a cache item.

type MemCache

type MemCache struct {
	gcore.Cache
	// contains filtered or unexported fields
}

func Memory

func Memory(id ...string) *MemCache

Memory acquires a memory cache object associated the id, id default is : `default`

func NewMemCache

func NewMemCache(cfg interface{}) *MemCache

func (*MemCache) Clear

func (s *MemCache) Clear() error

func (*MemCache) Decr

func (s *MemCache) Decr(key string) (v int64, err error)

func (*MemCache) DecrN

func (s *MemCache) DecrN(key string, n int64) (v int64, err error)

func (*MemCache) Del

func (s *MemCache) Del(key string) error

func (*MemCache) DelMulti

func (s *MemCache) DelMulti(keys []string) (err error)

func (*MemCache) Get

func (s *MemCache) Get(key string) (string, error)

func (*MemCache) GetMulti

func (s *MemCache) GetMulti(keys []string) (map[string]string, error)

func (*MemCache) Has

func (s *MemCache) Has(key string) (bool, error)

func (*MemCache) Incr

func (s *MemCache) Incr(key string) (v int64, err error)

func (*MemCache) IncrN

func (s *MemCache) IncrN(key string, n int64) (v int64, err error)

func (*MemCache) Set

func (s *MemCache) Set(key string, value string, ttl time.Duration) error

func (*MemCache) SetMulti

func (s *MemCache) SetMulti(values map[string]string, ttl time.Duration) (err error)

func (*MemCache) String

func (s *MemCache) String() string

type MemCacheConfig

type MemCacheConfig struct {
	CleanupInterval time.Duration
}

func NewMemCacheConfig

func NewMemCacheConfig() *MemCacheConfig

type MemoryCache

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

func NewMemoryCache

func NewMemoryCache(defaultExpiration, cleanupInterval time.Duration) *MemoryCache

NewMemoryCache returns a new cache with a given default expiration duration and cleanup interval. If the expiration duration is less than one (or NoExpiration), the items in the cache never expire (by default), and must be deleted manually. If the cleanup interval is less than one, expired items are not deleted from the cache before calling c.DeleteExpired().

func NewMemoryCacheFrom

func NewMemoryCacheFrom(defaultExpiration, cleanupInterval time.Duration, items map[string]MemoryCacheItem) *MemoryCache

NewMemoryCacheFrom returns a new cache with a given default expiration duration and cleanup interval. If the expiration duration is less than one (or NoExpiration), the items in the cache never expire (by default), and must be deleted manually. If the cleanup interval is less than one, expired items are not deleted from the cache before calling c.DeleteExpired().

NewFrom() also accepts an items map which will serve as the underlying map for the cache. This is useful for starting from a deserialized cache (serialized using e.g. gob.Encode() on c.MemoryCacheItems()), or passing in e.g. make(map[string]MemoryCacheItem, 500) to improve startup performance when the cache is expected to reach a certain minimum size.

Only the cache's methods synchronize access to this map, so it is not recommended to keep any references to the map around after creating a cache. If need be, the map can be accessed at a later point using c.MemoryCacheItems() (subject to the same caveat.)

Note regarding serialization: When using e.g. gob, make sure to gob.Register() the individual types stored in the cache before encoding a map retrieved with c.MemoryCacheItems(), and to register those same types before decoding a blob containing an items map.

func (MemoryCache) Add

func (c MemoryCache) Add(k string, x interface{}, d time.Duration) error

Add an item to the cache only if an item doesn't already exist for the given key, or if the existing item has expired. Returns an error otherwise.

func (MemoryCache) Decrement

func (c MemoryCache) Decrement(k string, n int64) error

Decrement an item of type int, int8, int16, int32, int64, uintptr, uint, uint8, uint32, or uint64, float32 or float64 by n. Returns an error if the item's value is not an integer, if it was not found, or if it is not possible to decrement it by n. To retrieve the decremented value, use one of the specialized methods, e.g. DecrementInt64.

func (MemoryCache) DecrementFloat

func (c MemoryCache) DecrementFloat(k string, n float64) error

Decrement an item of type float32 or float64 by n. Returns an error if the item's value is not floating point, if it was not found, or if it is not possible to decrement it by n. Pass a negative number to decrement the value. To retrieve the decremented value, use one of the specialized methods, e.g. DecrementFloat64.

func (MemoryCache) DecrementFloat32

func (c MemoryCache) DecrementFloat32(k string, n float32) (float32, error)

Decrement an item of type float32 by n. Returns an error if the item's value is not an float32, or if it was not found. If there is no error, the decremented value is returned.

func (MemoryCache) DecrementFloat64

func (c MemoryCache) DecrementFloat64(k string, n float64) (float64, error)

Decrement an item of type float64 by n. Returns an error if the item's value is not an float64, or if it was not found. If there is no error, the decremented value is returned.

func (MemoryCache) DecrementInt

func (c MemoryCache) DecrementInt(k string, n int) (int, error)

Decrement an item of type int by n. Returns an error if the item's value is not an int, or if it was not found. If there is no error, the decremented value is returned.

func (MemoryCache) DecrementInt8

func (c MemoryCache) DecrementInt8(k string, n int8) (int8, error)

Decrement an item of type int8 by n. Returns an error if the item's value is not an int8, or if it was not found. If there is no error, the decremented value is returned.

func (MemoryCache) DecrementInt16

func (c MemoryCache) DecrementInt16(k string, n int16) (int16, error)

Decrement an item of type int16 by n. Returns an error if the item's value is not an int16, or if it was not found. If there is no error, the decremented value is returned.

func (MemoryCache) DecrementInt32

func (c MemoryCache) DecrementInt32(k string, n int32) (int32, error)

Decrement an item of type int32 by n. Returns an error if the item's value is not an int32, or if it was not found. If there is no error, the decremented value is returned.

func (MemoryCache) DecrementInt64

func (c MemoryCache) DecrementInt64(k string, n int64) (int64, error)

Decrement an item of type int64 by n. Returns an error if the item's value is not an int64, or if it was not found. If there is no error, the decremented value is returned.

func (MemoryCache) DecrementUint

func (c MemoryCache) DecrementUint(k string, n uint) (uint, error)

Decrement an item of type uint by n. Returns an error if the item's value is not an uint, or if it was not found. If there is no error, the decremented value is returned.

func (MemoryCache) DecrementUint8

func (c MemoryCache) DecrementUint8(k string, n uint8) (uint8, error)

Decrement an item of type uint8 by n. Returns an error if the item's value is not an uint8, or if it was not found. If there is no error, the decremented value is returned.

func (MemoryCache) DecrementUint16

func (c MemoryCache) DecrementUint16(k string, n uint16) (uint16, error)

Decrement an item of type uint16 by n. Returns an error if the item's value is not an uint16, or if it was not found. If there is no error, the decremented value is returned.

func (MemoryCache) DecrementUint32

func (c MemoryCache) DecrementUint32(k string, n uint32) (uint32, error)

Decrement an item of type uint32 by n. Returns an error if the item's value is not an uint32, or if it was not found. If there is no error, the decremented value is returned.

func (MemoryCache) DecrementUint64

func (c MemoryCache) DecrementUint64(k string, n uint64) (uint64, error)

Decrement an item of type uint64 by n. Returns an error if the item's value is not an uint64, or if it was not found. If there is no error, the decremented value is returned.

func (MemoryCache) DecrementUintptr

func (c MemoryCache) DecrementUintptr(k string, n uintptr) (uintptr, error)

Decrement an item of type uintptr by n. Returns an error if the item's value is not an uintptr, or if it was not found. If there is no error, the decremented value is returned.

func (MemoryCache) Delete

func (c MemoryCache) Delete(k string)

Delete an item from the cache. Does nothing if the key is not in the cache.

func (MemoryCache) DeleteExpired

func (c MemoryCache) DeleteExpired()

Delete all expired items from the cache.

func (MemoryCache) Flush

func (c MemoryCache) Flush()

Delete all items from the cache.

func (MemoryCache) Get

func (c MemoryCache) Get(k string) (interface{}, bool)

Get an item from the cache. Returns the item or nil, and a bool indicating whether the key was found.

func (MemoryCache) GetWithExpiration

func (c MemoryCache) GetWithExpiration(k string) (interface{}, time.Time, bool)

GetWithExpiration returns an item and its expiration time from the cache. It returns the item or nil, the expiration time if one is set (if the item never expires a zero value for time.Time is returned), and a bool indicating whether the key was found.

func (MemoryCache) Increment

func (c MemoryCache) Increment(k string, n int64) error

Increment an item of type int, int8, int16, int32, int64, uintptr, uint, uint8, uint32, or uint64, float32 or float64 by n. Returns an error if the item's value is not an integer, if it was not found, or if it is not possible to increment it by n. To retrieve the incremented value, use one of the specialized methods, e.g. IncrementInt64.

func (MemoryCache) IncrementFloat

func (c MemoryCache) IncrementFloat(k string, n float64) error

Increment an item of type float32 or float64 by n. Returns an error if the item's value is not floating point, if it was not found, or if it is not possible to increment it by n. Pass a negative number to decrement the value. To retrieve the incremented value, use one of the specialized methods, e.g. IncrementFloat64.

func (MemoryCache) IncrementFloat32

func (c MemoryCache) IncrementFloat32(k string, n float32) (float32, error)

Increment an item of type float32 by n. Returns an error if the item's value is not an float32, or if it was not found. If there is no error, the incremented value is returned.

func (MemoryCache) IncrementFloat64

func (c MemoryCache) IncrementFloat64(k string, n float64) (float64, error)

Increment an item of type float64 by n. Returns an error if the item's value is not an float64, or if it was not found. If there is no error, the incremented value is returned.

func (MemoryCache) IncrementInt

func (c MemoryCache) IncrementInt(k string, n int) (int, error)

Increment an item of type int by n. Returns an error if the item's value is not an int, or if it was not found. If there is no error, the incremented value is returned.

func (MemoryCache) IncrementInt8

func (c MemoryCache) IncrementInt8(k string, n int8) (int8, error)

Increment an item of type int8 by n. Returns an error if the item's value is not an int8, or if it was not found. If there is no error, the incremented value is returned.

func (MemoryCache) IncrementInt16

func (c MemoryCache) IncrementInt16(k string, n int16) (int16, error)

Increment an item of type int16 by n. Returns an error if the item's value is not an int16, or if it was not found. If there is no error, the incremented value is returned.

func (MemoryCache) IncrementInt32

func (c MemoryCache) IncrementInt32(k string, n int32) (int32, error)

Increment an item of type int32 by n. Returns an error if the item's value is not an int32, or if it was not found. If there is no error, the incremented value is returned.

func (MemoryCache) IncrementInt64

func (c MemoryCache) IncrementInt64(k string, n int64) (int64, error)

Increment an item of type int64 by n. Returns an error if the item's value is not an int64, or if it was not found. If there is no error, the incremented value is returned.

func (MemoryCache) IncrementUint

func (c MemoryCache) IncrementUint(k string, n uint) (uint, error)

Increment an item of type uint by n. Returns an error if the item's value is not an uint, or if it was not found. If there is no error, the incremented value is returned.

func (MemoryCache) IncrementUint8

func (c MemoryCache) IncrementUint8(k string, n uint8) (uint8, error)

Increment an item of type uint8 by n. Returns an error if the item's value is not an uint8, or if it was not found. If there is no error, the incremented value is returned.

func (MemoryCache) IncrementUint16

func (c MemoryCache) IncrementUint16(k string, n uint16) (uint16, error)

Increment an item of type uint16 by n. Returns an error if the item's value is not an uint16, or if it was not found. If there is no error, the incremented value is returned.

func (MemoryCache) IncrementUint32

func (c MemoryCache) IncrementUint32(k string, n uint32) (uint32, error)

Increment an item of type uint32 by n. Returns an error if the item's value is not an uint32, or if it was not found. If there is no error, the incremented value is returned.

func (MemoryCache) IncrementUint64

func (c MemoryCache) IncrementUint64(k string, n uint64) (uint64, error)

Increment an item of type uint64 by n. Returns an error if the item's value is not an uint64, or if it was not found. If there is no error, the incremented value is returned.

func (MemoryCache) IncrementUintptr

func (c MemoryCache) IncrementUintptr(k string, n uintptr) (uintptr, error)

Increment an item of type uintptr by n. Returns an error if the item's value is not an uintptr, or if it was not found. If there is no error, the incremented value is returned.

func (MemoryCache) ItemCount

func (c MemoryCache) ItemCount() int

Returns the number of items in the cache. This may include items that have expired, but have not yet been cleaned up.

func (MemoryCache) Load

func (c MemoryCache) Load(r io.Reader) error

Add (Gob-serialized) cache items from an io.Reader, excluding any items with keys that already exist (and haven't expired) in the current cache.

NOTE: This method is deprecated in favor of c.MemoryCacheItems() and NewFrom() (see the documentation for NewFrom().)

func (MemoryCache) LoadFile

func (c MemoryCache) LoadFile(fname string) error

Load and add cache items from the given filename, excluding any items with keys that already exist in the current cache.

NOTE: This method is deprecated in favor of c.MemoryCacheItems() and NewFrom() (see the documentation for NewFrom().)

func (MemoryCache) MemoryCacheItems

func (c MemoryCache) MemoryCacheItems() map[string]MemoryCacheItem

Copies all unexpired items in the cache into a new map and returns it.

func (MemoryCache) OnEvicted

func (c MemoryCache) OnEvicted(f func(string, interface{}))

Sets an (optional) function that is called with the key and value when an item is evicted from the cache. (Including when it is deleted manually, but not when it is overwritten.) Set to nil to disable.

func (MemoryCache) Replace

func (c MemoryCache) Replace(k string, x interface{}, d time.Duration) error

Set a new value for the cache key only if it already exists, and the existing item hasn't expired. Returns an error otherwise.

func (MemoryCache) Save

func (c MemoryCache) Save(w io.Writer) (err error)

Write the cache's items (using Gob) to an io.Writer.

NOTE: This method is deprecated in favor of c.MemoryCacheItems() and NewFrom() (see the documentation for NewFrom().)

func (MemoryCache) SaveFile

func (c MemoryCache) SaveFile(fname string) error

Save the cache's items to the given filename, creating the file if it doesn't exist, and overwriting it if it does.

NOTE: This method is deprecated in favor of c.MemoryCacheItems() and NewFrom() (see the documentation for NewFrom().)

func (MemoryCache) Set

func (c MemoryCache) Set(k string, x interface{}, d time.Duration)

Add an item to the cache, replacing any existing item. If the duration is 0 (DefaultExpiration), the cache's default expiration time is used. If it is -1 (NoExpiration), the item never expires.

func (MemoryCache) SetDefault

func (c MemoryCache) SetDefault(k string, x interface{})

Add an item to the cache, replacing any existing item, using the default expiration.

type MemoryCacheItem

type MemoryCacheItem struct {
	Object     interface{}
	Expiration int64
}

func (MemoryCacheItem) Expired

func (item MemoryCacheItem) Expired() bool

Expired returns true if the item has expired.

type RedisCache

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

func NewRedisCache

func NewRedisCache(cfg interface{}) *RedisCache

NewRedisCache returns a new redis cache object.

func Redis

func Redis(id ...string) *RedisCache

Redis acquires a redis cache object associated the id, id default is : `default`

func (*RedisCache) Clear

func (c *RedisCache) Clear() error

Clear all caches

func (*RedisCache) Decr

func (c *RedisCache) Decr(key string) (val int64, err error)

Decr value by key

func (*RedisCache) DecrN

func (c *RedisCache) DecrN(key string, n int64) (val int64, err error)

DecrN value N by key

func (*RedisCache) Del

func (c *RedisCache) Del(key string) (err error)

Del value by key

func (*RedisCache) DelMulti

func (c *RedisCache) DelMulti(keys []string) (err error)

DelMulti values by keys

func (*RedisCache) Get

func (c *RedisCache) Get(key string) (val string, err error)

Get value by key

func (*RedisCache) GetMulti

func (c *RedisCache) GetMulti(keys []string) (map[string]string, error)

GetMulti values by keys

func (*RedisCache) Has

func (c *RedisCache) Has(key string) (bool, error)

Has cache key

func (*RedisCache) Incr

func (c *RedisCache) Incr(key string) (val int64, err error)

Incr value by key

func (*RedisCache) IncrN

func (c *RedisCache) IncrN(key string, n int64) (val int64, err error)

IncrN value N by key

func (*RedisCache) Pool

func (c *RedisCache) Pool() *redis.Pool

func (*RedisCache) Set

func (c *RedisCache) Set(key string, val string, ttl time.Duration) (err error)

Set value by key

func (*RedisCache) SetMulti

func (c *RedisCache) SetMulti(values map[string]string, ttl time.Duration) (err error)

SetMulti values

func (*RedisCache) String

func (c *RedisCache) String() string

String get

type RedisCacheConfig

type RedisCacheConfig struct {
	Debug           bool
	Prefix          string
	Logger          gcore.Logger
	Addr            string
	Password        string
	DBNum           int
	MaxIdle         int
	MaxActive       int
	IdleTimeout     time.Duration
	Wait            bool
	MaxConnLifetime time.Duration
	Timeout         time.Duration
}

func NewRedisCacheConfig

func NewRedisCacheConfig() *RedisCacheConfig

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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