remember

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: May 4, 2024 License: MIT Imports: 10 Imported by: 0

README

Built with GoLang Version License Go Report Card

Remember

Package remember provides an easy way to implement a Redis or Badger cache in your Go application.

Installation

Install it in the usual way:

go get -u github.com/tsawler/remember

Usage

Create an instance of the remember.Cache type by using the remember.New() function, and optionally passing it a remember.Options variable:

cache := remember.New() // Will use default options, suitable for development.

Or, specifying options:

ops := remember.Options{
    Server:   "localhost"      // The server where Redis exists.
    Port:     "6379"           // The port Redis is listening on.
    Password: "some_password"  // The password for Redis.
    Prefix:   "myapp"          // A prefix to use for all keys for this client. Useful when multiple clients use the same database.
    DB:       1                // Database. Specifying 0 (the default) means use the default database.
    BadgerPath string          // The location for the badger database on disk.
}

cache := remember.New(ops)

Example Program

package main

import (
	"encoding/gob"
	"fmt"
	"github.com/tsawler/remember"
	"log"
	"os"
	"time"
)

type Student struct {
	Name string
	Age  int
}

func main() {
	// For non-scalar types, you must register the type using gob.Register.
	gob.Register(Student{})
	gob.Register(time.Time{})
	gob.Register(map[string]string{})

	// Connect to Redis.
	cache, _ := remember.New("redis")
	// close the database pool when finished.
	defer cache.Close()
	
	// Or create & connect to a Badger database. Nothing else changes.
	// cache, _ := remember.New("badger", remember.Options{BadgerPath: "./badger"})

	// Store a simple string in the cache.
	fmt.Println("Putting value in the cache with key of foo")
	err := cache.Set("foo", "bar")
	if err != nil {
		fmt.Println("Error getting foo:", err)
		os.Exit(1)
	}

	fmt.Println("Putting an int value into the cache")
	err = cache.Set("intval", 10)
	if err != nil {
		fmt.Println("Error getting foo:", err)
		os.Exit(1)
	}

	fmt.Println("Pulling values out")
	s, err := cache.Get("foo")
	if err != nil {
		fmt.Println("Error getting foo:", err)
		os.Exit(1)
	}

	i, err := cache.GetInt("intval")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	fmt.Printf("foo: %s, intval: %d\n", s, i)

	// Create an object to store in the cache.
	mary := Student{Name: "Mary", Age: 10}

	// Put the value into the cache with the key student_mary.
	fmt.Println("Putting student_mary into the cache...")
	err = cache.Set("student_mary", mary)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// Pull the value out of the cache.
	fmt.Println("Pulling student_mary from the cache....")
	fromCache, err := cache.Get("student_mary")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	student := fromCache.(Student)

	fmt.Printf("%s is %d years old\n", student.Name, student.Age)

	fmt.Println("student_mary is in cache:", cache.Has("student_mary"))
	fmt.Println("Deleting student_mary from the cache....")
	_ = cache.Forget("student_mary")
	fmt.Println("student_mary is in cache after delete:", cache.Has("student_mary"))

	now := time.Now()

	// Put a time.Time type in the cache.
	err = cache.Set("now", now)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// Retrieve time.Time from the cache.
	n, err := cache.GetTime("now")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	fmt.Println(n.Format("2006-01-02 03:04:05 PM"))

	// Create a map.
	myMap := make(map[string]string)
	myMap["1"] = "A"
	myMap["2"] = "B"
	myMap["3"] = "C"

	// Put the map in the cache.
	err = cache.Set("mymap", myMap)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// Pull the map out of the cache.
	m, err := cache.Get("mymap")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	myMap2 := m.(map[string]string)
	fmt.Println("1 is", myMap2["1"])

	fmt.Println("Setting 3 foo vars....")
	cache.Set("fooa", "bar")
	cache.Set("foob", "bar")
	cache.Set("fooc", "bar")

	// Remove all entries from the cache with the prefix "foo".
	err = cache.EmptyByMatch("foo")
	if err != nil {
		log.Println(err)
	}

	fmt.Println("cache has fooa:", cache.Has("fooa"))
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BadgerCache added in v1.1.0

type BadgerCache struct {
	Conn   *badger.DB
	Prefix string
}

BadgerCache is the type for a Badger database cache.

func (*BadgerCache) Close added in v1.1.0

func (b *BadgerCache) Close()

Close closes the badger database.

func (*BadgerCache) Empty added in v1.1.0

func (b *BadgerCache) Empty() error

Empty removes all entries in Badger.

func (*BadgerCache) EmptyByMatch added in v1.1.0

func (b *BadgerCache) EmptyByMatch(str string) error

EmptyByMatch removes all entries in Redis which have the prefix match.

func (*BadgerCache) Forget added in v1.1.0

func (b *BadgerCache) Forget(str string) error

Forget removes an item from the cache, by key.

func (*BadgerCache) Get added in v1.1.0

func (b *BadgerCache) Get(str string) (any, error)

Get attempts to retrieve a value from the cache.

func (*BadgerCache) GetInt added in v1.1.0

func (b *BadgerCache) GetInt(key string) (int, error)

GetInt is a convenience method which retrieves a value from the cache, converts it to an int, and returns it.

func (*BadgerCache) GetString added in v1.1.0

func (b *BadgerCache) GetString(key string) (string, error)

GetString is a convenience method which retrieves a value from the cache and returns it as a string.

func (*BadgerCache) GetTime added in v1.1.0

func (b *BadgerCache) GetTime(key string) (time.Time, error)

GetTime retrieves a value from the cache by the specified key and returns it as time.Time.

func (*BadgerCache) Has added in v1.1.0

func (b *BadgerCache) Has(str string) bool

func (*BadgerCache) Set added in v1.1.0

func (b *BadgerCache) Set(str string, value any, expires ...time.Duration) error

Set puts a value into Badger. The final parameter, expires, is optional.

type CacheEntry

type CacheEntry map[string]interface{}

CacheEntry is a map to hold values, so we can serialize them.

type CacheInterface added in v1.1.0

type CacheInterface interface {
	Empty() error
	EmptyByMatch(match string) error
	Forget(key string) error
	Get(key string) (any, error)
	GetInt(key string) (int, error)
	GetString(key string) (string, error)
	GetTime(key string) (time.Time, error)
	Has(key string) bool
	Set(key string, data any, expires ...time.Duration) error
	Close()
}

CacheInterface is the interface which anything providing cache functionality must satisfy.

func New

func New(cacheType string, o ...Options) (CacheInterface, error)

New is a factory method which returns an instance of *RedisCache which satisfies the CacheInterface.

type Options

type Options struct {
	Server     string // The server where Redis exists.
	Port       string // The port Redis is listening on.
	Password   string // The password for Redis.
	Prefix     string // A prefix to use for all keys for this client.
	DB         int    // Database. Specifying 0 (the default) means use the default database.
	BadgerPath string // The location for the badger database on disk.
}

Options is the type used to configure a RedisCache object.

type RedisCache added in v1.1.0

type RedisCache struct {
	Conn         *redis.Client
	BadgerClient *badger.DB
	Prefix       string
}

RedisCache is the type for a Redis-based cache.

func (*RedisCache) Close added in v1.1.0

func (c *RedisCache) Close()

Close closes the pool of redis connections

func (*RedisCache) Empty added in v1.1.0

func (c *RedisCache) Empty() error

Empty removes all entries in Redis for a given client.

func (*RedisCache) EmptyByMatch added in v1.1.0

func (c *RedisCache) EmptyByMatch(match string) error

EmptyByMatch removes all entries in Redis which have the prefix match.

func (*RedisCache) Forget added in v1.1.0

func (c *RedisCache) Forget(key string) error

Forget removes an item from the cache, by key.

func (*RedisCache) Get added in v1.1.0

func (c *RedisCache) Get(key string) (any, error)

Get attempts to retrieve a value from the cache.

func (*RedisCache) GetInt added in v1.1.0

func (c *RedisCache) GetInt(key string) (int, error)

GetInt is a convenience method which retrieves a value from the cache, converts it to an int, and returns it.

func (*RedisCache) GetString added in v1.1.0

func (c *RedisCache) GetString(key string) (string, error)

GetString is a convenience method which retrieves a value from the cache and returns it as a string.

func (*RedisCache) GetTime added in v1.1.0

func (c *RedisCache) GetTime(key string) (time.Time, error)

GetTime retrieves a value from the cache by the specified key and returns it as time.Time.

func (*RedisCache) Has added in v1.1.0

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

Has checks to see if the supplied key is in the cache and returns true if found, otherwise false.

func (*RedisCache) Set added in v1.1.0

func (c *RedisCache) Set(key string, data any, expires ...time.Duration) error

Set puts a value into Redis. The final parameter, expires, is optional.

Jump to

Keyboard shortcuts

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