inmem

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Apr 15, 2025 License: MIT Imports: 17 Imported by: 0

README

inmem

inmem is an in-memory cache library for Go, designed to provide a simple and efficient caching mechanism.

Features

  • In-Memory Caching: Store key-value pairs in memory for fast access.
  • Sharding: Distribute cache items across multiple shards for improved performance.
  • Transactions: Support for atomic and optimistic transactions.
  • Persistence: Periodically save cache data to disk and load it on startup.
  • Eviction: TTL based, LFU, LRU eviction policy for the keys.

Installation

To install the package, run:

go get github.com/achu-1612/inmem

Usage

Basic Usage
package main

import (
    "context"
    "fmt"
    "github.com/achu-1612/inmem"
)

func main() {
    cache, err := inmem.New(context.Background(), inmem.Options{})
    if err != nil {
        panic(err)
    }

    cache.Set("key", "value", 0)
    value, found := cache.Get("key")
    if found {
        fmt.Println("Found value:", value)
    } else {
        fmt.Println("Value not found")
    }
}
Sharded Cache
package main

import (
    "context"
    "github.com/achu-1612/inmem"
)

func main() {
    cache, err := inmem.New(context.Background(), inmem.Options{
        Sharding:   true,
        ShardCount: 4,
    })
    if err != nil {
        panic(err)
    }

    cache.Set("key", "value", 0)
    value, found := cache.Get("key")
    if found {
        fmt.Println("Found value:", value)
    } else {
        fmt.Println("Value not found")
    }
}
Transactions
package main

import (
    "context"
    "github.com/achu-1612/inmem"
)

func main() {
    cache, err := inmem.New(context.Background(), inmem.Options{
        TransactionType: inmem.TransactionTypeOptimistic,
    })
    if err != nil {
        panic(err)
    }

    cache.Begin()
    cache.Set("key", "value", 0)
    cache.Commit()

    value, found := cache.Get("key")
    if found {
        fmt.Println("Found value:", value)
    } else {
        fmt.Println("Value not found")
    }
}
Persistence
package main

import (
    "context"
    "github.com/achu-1612/inmem"
    "time"
)

func main() {
    cache, err := inmem.New(context.Background(), inmem.Options{
        Sync:           true,
        SyncInterval:   time.Minute,
        SyncFolderPath: "cache_data",
    })
    if err != nil {
        panic(err)
    }

    cache.Set("key", "value", 0)
    value, found := cache.Get("key")
    if found {
        fmt.Println("Found value:", value)
    } else {
        fmt.Println("Value not found")
    }
}
Eviction
package main

import (
    "context"
    "github.com/achu-1612/inmem"
    "github.com/achu-1612/inmem/eviction"
)

func main() {
    cache, err := inmem.New(context.Background(), inmem.Options{
        EvictionPolicy: eviction.PolicyLRU,,
        MaxSize: 2,
    })
    if err != nil {
        panic(err)
    }

    cache.Set("key1", "value", 0)
    cache.Set("key2", "value", 0)
    cache.Get("key2")
    cache.Set("key3", "value", 0) // key1 will be evicted as key2 has access frequency as 2 and key1 has 1
}
Just the LFU/LRU cache

package main

import (
    "context"
    "github.com/achu-1612/inmem/eviction"
)

func main() {
    cache, err := eviction.New(eviction.Options{
        Policy: eviction.PolicyLFU, // eviction.PolicyLRU can be used to LRU cache
        Capacity: 2,
        DeleteFinalizer: nil, // optional
        EvictFinalizer: nil,
    })
    if err != nil {
        panic(err)
    }

    cache.Set("key1", "value")
    cache.Set("key2", "value")
    cache.Get("key2")
    cache.Set("key3", "value" // key1 will be evicted as key2 has access frequency as 2 and key1 has 1
}
// Implment LFUResource, an entry for the LFU cache.
// If not default eviction entry will be use to deal with the cache data.

License

This project is licensed under the MIT License.

Contributing

Contributions are welcome! Open an issue or submit a pull request.

Contact

For questions or support, reach out to me

Documentation

Overview

Package inmem is a generated GoMock package.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrorInTransaction  = errors.New("already in transaction")
	ErrNotInTransaction = errors.New("not in transaction")
)

Functions

This section is empty.

Types

type Cache

type Cache interface {
	// Size returns the number of items in the cache.
	Size() int

	// Get returns a value from the cache given a key.
	Get(key string) (any, bool)

	// Set sets a key in the cache with a value and a time-to-live (TTL).
	Set(key string, value any, ttl int64)

	// Delete deletes a key from the cache.
	Delete(key string)

	// Clear clears all items from the cache.
	Clear()

	// Dump saves the cache to the configured directory.
	Dump() error

	// TransactionType returns the type of the transaction.
	TransactionType() TransactionType

	// Begin starts a transaction.
	Begin() error

	// Commit commits a transaction.
	Commit() error

	// Rollback rolls back a transaction.
	Rollback() error
}

Cache is the interface that defines the methods for a cache store.

func New

func New(ctx context.Context, opt Options) (Cache, error)

New creates a new in-memory cache

func NewCache

func NewCache(ctx context.Context, opt Options, index int) (Cache, error)

New returns a new Cache instance.

func NewShardedCache

func NewShardedCache(ctx context.Context, opt Options) (Cache, error)

NewShardedCache returns a new sharded cache instance.

type Item

type Item struct {
	// Object is the actual data to be stored in the cache.
	Object any

	// Expiration is the unix time when the entry will get expired/evicted from the cache.
	Expiration int64
}

Item represents a cache item.

func (*Item) Expired

func (i *Item) Expired(now time.Time) bool

Expired returns true if the item has expired.

type MockCache

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

MockCache is a mock of Cache interface.

func NewMockCache

func NewMockCache(ctrl *gomock.Controller) *MockCache

NewMockCache creates a new mock instance.

func (*MockCache) Begin

func (m *MockCache) Begin() error

Begin mocks base method.

func (*MockCache) Clear

func (m *MockCache) Clear()

Clear mocks base method.

func (*MockCache) Commit

func (m *MockCache) Commit() error

Commit mocks base method.

func (*MockCache) Delete

func (m *MockCache) Delete(key string)

Delete mocks base method.

func (*MockCache) Dump

func (m *MockCache) Dump() error

Dump mocks base method.

func (*MockCache) EXPECT

func (m *MockCache) EXPECT() *MockCacheMockRecorder

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockCache) Get

func (m *MockCache) Get(key string) (any, bool)

Get mocks base method.

func (*MockCache) Rollback

func (m *MockCache) Rollback() error

Rollback mocks base method.

func (*MockCache) Set

func (m *MockCache) Set(key string, value any, ttl int64)

Set mocks base method.

func (*MockCache) Size

func (m *MockCache) Size() int

Size mocks base method.

func (*MockCache) TransactionType

func (m *MockCache) TransactionType() TransactionType

TransactionType mocks base method.

type MockCacheMockRecorder

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

MockCacheMockRecorder is the mock recorder for MockCache.

func (*MockCacheMockRecorder) Begin

func (mr *MockCacheMockRecorder) Begin() *gomock.Call

Begin indicates an expected call of Begin.

func (*MockCacheMockRecorder) Clear

func (mr *MockCacheMockRecorder) Clear() *gomock.Call

Clear indicates an expected call of Clear.

func (*MockCacheMockRecorder) Commit

func (mr *MockCacheMockRecorder) Commit() *gomock.Call

Commit indicates an expected call of Commit.

func (*MockCacheMockRecorder) Delete

func (mr *MockCacheMockRecorder) Delete(key any) *gomock.Call

Delete indicates an expected call of Delete.

func (*MockCacheMockRecorder) Dump

func (mr *MockCacheMockRecorder) Dump() *gomock.Call

Dump indicates an expected call of Dump.

func (*MockCacheMockRecorder) Get

func (mr *MockCacheMockRecorder) Get(key any) *gomock.Call

Get indicates an expected call of Get.

func (*MockCacheMockRecorder) Rollback

func (mr *MockCacheMockRecorder) Rollback() *gomock.Call

Rollback indicates an expected call of Rollback.

func (*MockCacheMockRecorder) Set

func (mr *MockCacheMockRecorder) Set(key, value, ttl any) *gomock.Call

Set indicates an expected call of Set.

func (*MockCacheMockRecorder) Size

func (mr *MockCacheMockRecorder) Size() *gomock.Call

Size indicates an expected call of Size.

func (*MockCacheMockRecorder) TransactionType

func (mr *MockCacheMockRecorder) TransactionType() *gomock.Call

TransactionType indicates an expected call of TransactionType.

type Options

type Options struct {
	// Finalizer is the finalizer function that is called when an item is evicted from the cache.
	// Note: When in transaction, the finalizer is called after the transaction is committed.
	Finalizer func(string, any)

	// TransactionType is the type of transaction to be used.
	// Options are:
	// 1. Optimistic
	// 2. Pessimistic
	TransactionType TransactionType

	// Sync enables the cache to be synchronized with a folder.
	// When sharding is enabled, the defined folder will container multiple .gob files (one per peach shard)
	Sync bool
	// SyncFolderPath is the path to the folder where the cache will be synchronized.
	SyncFolderPath string
	// SyncInterval is the interval at which the cache will be synchronized.
	SyncInterval time.Duration

	// Sharding enables the cache to be sharded.
	Sharding bool
	// ShardCount is the number of shards to be created.
	ShardCount uint32

	// SupressLog suppresses the logs.
	SupressLog bool
	// DebugLogs enables the debug logs.
	DebugLogs bool

	// EvictionPolicy is the eviction policy to be used.
	EvictionPolicy eviction.Policy

	// MaxSize is the maximum size of the cache, after this size is reached, the cache will start evicting items.
	MaxSize int
}

Options represents the options for the cache store initialization.

type TransactionType

type TransactionType string
const (
	TransactionTypeAtomic     TransactionType = "atomic"
	TransactionTypeOptimistic TransactionType = "optimistic"
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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