cache

package module
v1.0.5 Latest Latest
Warning

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

Go to latest
Published: Aug 28, 2024 License: MIT Imports: 25 Imported by: 0

README

Multi-Level Cache Library

目錄

簡介

這個 MultiLevelCache 是一個多層級緩存庫,它結合了本地內存緩存和 Redis 遠端緩存的特性,提供了一個具有高性能和可擴展性的緩存解決方案。此緩存系統適合需要高頻讀取和寫入操作的應用場景。

特性

  • 支援多層緩存(本地緩存和 Redis 遠端緩存)
  • 支援布隆過濾器以減少無效查詢
  • 支援斷路器(Circuit Breaker)來提升系統穩定性
  • 自適應 TTL 管理和預取策略
  • 支援一致性哈希(Consistent Hashing)來有效分佈緩存負載
  • 支援單飛請求合併(Request Coalescing)來減少重複查詢

安裝

使用以下指令安裝所需的 Go 模組:

go get -u goflare.io/cache

快速開始

以下是如何初始化 MultiLevelCache 並進行基本操作的範例:

package main

import (
	"context"
	"fmt"
	"time"

	"goflare.io/cache"
	"go.uber.org/zap"
)

func main() {
	// 初始化 logger
	logger, _ := zap.NewProduction()

	// 創建 MultiLevelCache 配置
	config := cache.Config{
		LocalExpiration:  5 * time.Minute,
		CleanupInterval:  10 * time.Minute,
		EnableLocalCache: true,
		MaxLocalSize:     1000000,
		RedisConfig: &redis.Options{
			Addr: "localhost:6379",
		},
		Logger: logger,
	}

	// 創建 MultiLevelCache 實例
	multiLevelCache, err := cache.NewMultiLevelCache(
		cache.WithLogger(logger),
		cache.WithLocalExpiration(10*time.Minute),
		cache.WithRedisAddress("localhost:6379"),
	)
	if err != nil {
		logger.Fatal("無法創建 MultiLevelCache", zap.Error(err))
	}

	// 設置緩存
	err = multiLevelCache.Set(context.Background(), "myKey", "myValue", 5*time.Minute)
	if err != nil {
		logger.Error("設置緩存失敗", zap.Error(err))
	}

	// 獲取緩存
	var value string
	found, err := multiLevelCache.Get(context.Background(), "myKey", &value)
	if err != nil {
		logger.Error("獲取緩存失敗", zap.Error(err))
	} 
	
	if found {
		fmt.Println("獲取到緩存:", value)
	} else {
		fmt.Println("緩存不存在")
	}
}

配置選項

MultiLevelCache 提供多種配置選項,以便您根據需要自定義緩存行為。以下是一些常用的配置選項:

  • LocalExpiration:本地緩存過期時間
  • CleanupInterval:清理間隔
  • EnableLocalCache:是否啟用本地緩存
  • MaxLocalSize:本地緩存的最大大小
  • RedisConfig:Redis 配置,包括地址、密碼等
  • BloomFilterConfig:布隆過濾器的配置
  • GlobalCircuitBreaker:全局斷路器的設置
  • KeyCircuitBreaker:每個鍵的斷路器設置
  • RetrierBackoff:重試器的退避策略
  • ShardCount:分片數量
  • AdaptiveTTLConfig:自適應 TTL 配置
  • CoalescingConfig:請求合併配置
  • PrefetchConfig:預取配置

使用案例

設置和獲取緩存
err := multiLevelCache.Set(context.Background(), "user:123", userObject, 10*time.Minute)
if err != nil {
    log.Fatalf("設置緩存失敗: %v", err)
}

var user User
found, err := multiLevelCache.Get(context.Background(), "user:123", &user)
if err != nil {
    log.Fatalf("獲取緩存失敗: %v", err)
}
if found {
    fmt.Println("用戶資料已獲取:", user)
} else {
    fmt.Println("用戶資料不存在於緩存中")
}
自適應 TTL 設置

自適應 TTL 根據緩存項的訪問頻率動態調整 TTL,提升緩存的有效性和效能。

multiLevelCache.Set(context.Background(), "session:456", sessionObject, cache.AdaptiveTTL)
預取常用緩存

使用預取策略來提前緩存常用資料,提升系統效能。

multiLevelCache.Prefetch(context.Background(), []string{"key1", "key2", "key3"})

使用情境

MultiLevelCache 非常適合以下使用情境:

  1. 高頻訪問的資料:例如用戶會話、認證票據等需要快速訪問的資料。
  2. 分佈式系統中的共享資料:在分佈式系統中,利用 Redis 做為遠端緩存,並在每個節點上使用本地緩存,降低對 Redis 的頻繁訪問。
  3. 頻繁讀寫操作的場景:適合用於需要頻繁讀寫的場景,如電子商務網站的產品目錄、價格和庫存資訊。
  4. 資料預熱:適用於需要提前緩存常用資料的場景,如熱門產品列表、常用查詢結果等。

如何貢獻

歡迎各種形式的貢獻,無論是提交 Bug 報告、改進程式碼、增加功能或更新文檔。如果您想要貢獻,請先閱讀我們的貢獻指南。

  1. Fork 本庫
  2. 創建您的特性分支 (git checkout -b feature/AmazingFeature)
  3. 提交您的更改 (git commit -m 'Add some AmazingFeature')
  4. 推送到分支 (git push origin feature/AmazingFeature)
  5. 開啟 Pull Request

感謝您對 MultiLevelCache 的支持!如有任何問題或建議,請隨時聯繫我們。

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrSetFailed      = errors.New("failed to set value in cache")
	ErrKeyNotFound    = errors.New("key not found")
	ErrMaxSizeReached = errors.New("max cache size reached")
	DefaultExpiration = 30 * time.Minute
)

Functions

This section is empty.

Types

type Entry

type Entry struct {
	Data       any
	Expiration time.Time
}

type LimitedCache

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

LimitedCache implements a size-limited cache

func NewLimitedCache

func NewLimitedCache(maxSize int64, numSegments int, defaultTTL time.Duration) (*LimitedCache, error)

NewLimitedCache creates a new instance of LimitedCache

func (*LimitedCache) AdjustTTLs added in v1.0.3

func (lc *LimitedCache) AdjustTTLs(ttlFunc func(string) time.Duration)

func (*LimitedCache) Close added in v1.0.3

func (lc *LimitedCache) Close()

func (*LimitedCache) Delete

func (lc *LimitedCache) Delete(ctx context.Context, key string)

func (*LimitedCache) Flush

func (lc *LimitedCache) Flush(ctx context.Context)

func (*LimitedCache) Get

func (lc *LimitedCache) Get(ctx context.Context, key string) (any, bool)

func (*LimitedCache) GetMetrics added in v1.0.1

func (lc *LimitedCache) GetMetrics() Metrics

func (*LimitedCache) GetMulti added in v1.0.1

func (lc *LimitedCache) GetMulti(ctx context.Context, keys []string) map[string]any

func (*LimitedCache) ItemCount

func (lc *LimitedCache) ItemCount() int

func (*LimitedCache) Set

func (lc *LimitedCache) Set(ctx context.Context, key string, value any, ttl ...time.Duration) error

func (*LimitedCache) SetDefaultTTL added in v1.0.1

func (lc *LimitedCache) SetDefaultTTL(ttl time.Duration)

func (*LimitedCache) SetEvictionCallback added in v1.0.1

func (lc *LimitedCache) SetEvictionCallback(callback func(key string, value any))

SetEvictionCallback 設置驅逐回調函數 SetEvictionCallback sets the eviction callback function

func (*LimitedCache) SetMulti added in v1.0.1

func (lc *LimitedCache) SetMulti(ctx context.Context, items map[string]any, ttl ...time.Duration) error

type Metrics added in v1.0.1

type Metrics struct {
	Hits      *atomic.Int64
	Misses    *atomic.Int64
	Evictions *atomic.Int64
	Size      *atomic.Int64
}

Metrics stores cache statistics

type MultiLevelCache

type MultiLevelCache struct {
	EncoderFunc func(w io.Writer) serialization.Encoder
	DecoderFunc func(r io.Reader) serialization.Decoder
	// contains filtered or unexported fields
}

MultiLevelCache 實現多層緩存系統

func NewMultiLevelCache

func NewMultiLevelCache(mlcConfig config.MLCConfig, client *redis.Client) (*MultiLevelCache, error)

NewMultiLevelCache 創建一個新的 MultiLevelCache 實例

func (*MultiLevelCache) Clear

func (c *MultiLevelCache) Clear(ctx context.Context) error

func (*MultiLevelCache) Close

func (c *MultiLevelCache) Close() error

func (*MultiLevelCache) Delete

func (c *MultiLevelCache) Delete(ctx context.Context, key string) error

func (*MultiLevelCache) Exists added in v1.0.1

func (c *MultiLevelCache) Exists(ctx context.Context, key string) (bool, error)

func (*MultiLevelCache) Get

func (c *MultiLevelCache) Get(ctx context.Context, key string, value any) (bool, error)

func (*MultiLevelCache) GetMulti

func (c *MultiLevelCache) GetMulti(ctx context.Context, keys []string) (map[string]any, error)

func (*MultiLevelCache) GetTTL added in v1.0.1

func (c *MultiLevelCache) GetTTL(ctx context.Context, key string) (time.Duration, error)

func (*MultiLevelCache) Incr added in v1.0.1

func (c *MultiLevelCache) Incr(ctx context.Context, key string) (int64, error)

func (*MultiLevelCache) Set

func (c *MultiLevelCache) Set(ctx context.Context, key string, value any, ttl ...time.Duration) error

func (*MultiLevelCache) SetMulti

func (c *MultiLevelCache) SetMulti(ctx context.Context, items map[string]any, ttl ...time.Duration) error

func (*MultiLevelCache) SetNX added in v1.0.1

func (c *MultiLevelCache) SetNX(ctx context.Context, key string, value any, ttl ...time.Duration) (bool, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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