Coder Social home page Coder Social logo

remember's Introduction

Built with GoLang Version License Go Report Card

Remember

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

Installation

Install it in the usual way:

go get -u github.com/tsawler/remember/v2

Usage

Create an instance of the remember.Cache type by using the remember.New(cacheType string, o ...*Options) function, and optionally passing it a remember.Options variable. cacheType can by redis, buntdb, or badger. The second parameter, o, is optional.

cache, err := remember.New("redis") // 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:       0                // Database. Specifying 0 (the default) means use the default database.
    BadgerPath: ""             // The location for the badger database on disk. Defaults to ./badger
    BuntDBPath: ""             // The location for the BuntDB database on disk. Use :memory: for in-memory.
}

cache, _ := remember.New(ops)

Example Program

package main

import (
	"encoding/gob"
	"fmt"
	"github.com/tsawler/remember/v2"
	"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()
	
	// Alternatively, use "badger" or "buntdb". Nothing else changes.
	//cache, _ := remember.New("badger")
	//cache, _ := remember.New("buntdb")

	// 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"))
}

remember's People

Contributors

tsawler avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.