cache

package module
v0.1.6 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2020 License: Apache-2.0 Imports: 8 Imported by: 11

README

go-cache

go-cache is a simple redis cache dependency system on-top of the famous redigo package

Go Build Status Report codecov Release GoDoc

Table of Contents

Installation

go-cache requires a supported release of Go.

$ go get -u github.com/mrz1836/go-cache

Documentation

You can view the generated documentation here.

Features
  • Cache Dependencies Between Keys (toggle functionality)
  • Connect via URL
  • Better Pool Management & Creation
  • Register Scripts
  • Helper Methods (Get, Set, HashGet, etc)
  • Basic Lock/Release (from bgentry lock.go)
Library Deployment

goreleaser for easy binary or library deployment to Github and can be installed via: brew install goreleaser.

The .goreleaser.yml file is used to configure goreleaser.

Use make release-snap to create a snapshot version of the release, and finally make release to ship to production.

Makefile Commands

View all makefile commands

$ make help

List of all current commands:

bench                          Run all benchmarks in the Go application
clean                          Remove previous builds and any test cache data
clean-mods                     Remove all the Go mod cache
coverage                       Shows the test coverage
godocs                         Sync the latest tag with GoDocs
help                           Show all make commands available
lint                           Run the Go lint application
release                        Full production release (creates release in Github)
release-test                   Full production test release (everything except deploy)
release-snap                   Test the full release (build binaries)
run-examples                   Runs all the examples
tag                            Generate a new tag and push (IE: make tag version=0.0.0)
tag-remove                     Remove a tag if found (IE: make tag-remove version=0.0.0)
tag-update                     Update an existing tag to current commit (IE: make tag-update version=0.0.0)
test                           Runs vet, lint and ALL tests
test-short                     Runs vet, lint and tests (excludes integration tests)
update                         Update all project dependencies
update-releaser                Update the goreleaser application
vet                            Run the Go vet application
Package Dependencies

Examples & Tests

All unit tests and examples run via Travis CI and uses Go version 1.14.x. View the deployment configuration file.

Run all tests (including integration tests)

$ make test

Run tests (excluding integration tests)

$ make test-short

Run the examples:

$ make run-examples

Benchmarks

Run the Go benchmarks:

$ make bench

Code Standards

Read more about this Go project's code standards.

Usage

View the examples

Basic implementation:

package main

import (
	"log"

	"github.com/mrz1836/go-cache"
)

func main() {

	// Create the pool and first connection
	_ = cache.Connect("redis://localhost:6379", 0, 10, 0, 240, true, redis.DialKeepAlive(10*time.Second))

	// Set a key
	_ = cache.Set("key-name", "the-value", "dependent-key-1", "dependent-key-2")

	// Get a key
	value, _ := cache.Get("key-name")
	log.Println("Got value:", value)
	// Output: Got Value: the-value

	// Kill keys by dependency
	keys, _ := cache.KillByDependency("dependent-key-1")
	log.Println("Keys Removed:", keys)
	// Output: Keys Removed: 2
}

Maintainers

MrZ MrZ
MrZ kayleg

Contributing

This project uses Gary Burd's Redigo package.

View the contributing guidelines and follow the code of conduct.

Support the development of this project 🙏

Donate

License

License

Documentation

Overview

Package cache is a simple redis cache dependency system on-top of the famous redigo package

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrLockMismatch = errors.New("key is locked with a different secret")

ErrLockMismatch is the error if the key is locked by someone else

Functions

func Connect

func Connect(url string, maxActiveConnections, idleConnections, maxConnLifetime, idleTimeout int, dependencyMode bool, options ...redis.DialOption) (err error)

Connect creates a new connection pool connected to the specified url

Example

ExampleConnect is an example of Connect() method

// Create a local connection
_ = Connect(connectionURL, maxActiveConnections, maxIdleConnections, maxConnLifetime, idleTimeout, true)

// Disconnect at end
defer Disconnect()

// Connected
fmt.Print("connected")
Output:
connected

func ConnectToURL

func ConnectToURL(urlString string, options ...redis.DialOption) (c redis.Conn, err error)

ConnectToURL connects via REDIS_URL Source: github.com/soveran/redisurl URL Format: redis://localhost:6379

Example

ExampleConnectToURL is an example of ConnectToURL() method

// Create a local connection
_, _ = ConnectToURL(connectionURL)

// Disconnect at end
defer Disconnect()

// Connected
fmt.Print("connected")
Output:
connected

func Delete added in v0.0.2

func Delete(keys ...string) (total int, err error)

Delete is an alias for KillByDependency()

Example

ExampleDelete is an example of Delete() method

// Create a local connection
_ = Connect(connectionURL, maxActiveConnections, maxIdleConnections, maxConnLifetime, idleTimeout, true)

// Disconnect at end
defer Disconnect()

// Set the key/value
_ = Set("example-destroy-cache", "my-value", "another-key")

// Delete keys
total, _ := Delete("another-key", "another-key-2")
fmt.Print(total, " deleted keys")
Output:
2 deleted keys

func DeleteWithoutDependency added in v0.0.8

func DeleteWithoutDependency(keys ...string) (total int, err error)

DeleteWithoutDependency will remove keys without using dependency script

Example

ExampleDeleteWithoutDependency is an example of DeleteWithoutDependency() method

// Create a local connection
_ = Connect(connectionURL, maxActiveConnections, maxIdleConnections, maxConnLifetime, idleTimeout, true)

// Disconnect at end
defer Disconnect()

// Set the key/value
_ = Set("example-destroy-cache-1", "my-value")
_ = Set("example-destroy-cache-2", "my-value")

// Delete keys
total, _ := DeleteWithoutDependency("example-destroy-cache-1", "example-destroy-cache-2")
fmt.Print(total, " deleted keys")
Output:
2 deleted keys

func DestroyCache

func DestroyCache() (err error)

DestroyCache will flush the entire redis server. It only removes keys, not scripts

Example

ExampleDestroyCache is an example of DestroyCache() method

// Create a local connection
_ = Connect(connectionURL, maxActiveConnections, maxIdleConnections, maxConnLifetime, idleTimeout, true)

// Disconnect at end
defer Disconnect()

// Set the key/value
_ = Set("example-destroy-cache", "my-value", "another-key")

// Set the expire
_ = DestroyCache()
fmt.Print("cache destroyed")
Output:
cache destroyed

func DidRegisterKillByDependencyScript

func DidRegisterKillByDependencyScript() bool

DidRegisterKillByDependencyScript returns true if the script has a sha from redis

Example

ExampleRegisterScripts is an example of RegisterScripts() method

// Create a local connection
_ = Connect(connectionURL, maxActiveConnections, maxIdleConnections, maxConnLifetime, idleTimeout, true)

// Disconnect at end
defer Disconnect()

// Fire
_ = DidRegisterKillByDependencyScript()
fmt.Print("registered")
Output:
registered

func Disconnect

func Disconnect()

Disconnect closes the connection pool

Example

ExampleDisconnect is an example of Disconnect() method

// Create a local connection
_ = Connect(connectionURL, maxActiveConnections, maxIdleConnections, maxConnLifetime, idleTimeout, true)

// Disconnect at end
Disconnect()

fmt.Print("disconnected")
Output:
disconnected

func Exists

func Exists(key string) (bool, error)

Exists checks if a key is present or not

Example

ExampleExists is an example of Exists() method

// Create a local connection
_ = Connect(connectionURL, maxActiveConnections, maxIdleConnections, maxConnLifetime, idleTimeout, true)

// Disconnect at end
defer Disconnect()

// Set the key/value
_ = Set("example-exists", "my-value", "another-key")

// Get the value
_, _ = Exists("example-exists")
fmt.Print("key exists")
Output:
key exists

func Expire

func Expire(key string, duration time.Duration) (err error)

Expire sets the expiration for a given key

Example

ExampleExpire is an example of Expire() method

// Create a local connection
_ = Connect(connectionURL, maxActiveConnections, maxIdleConnections, maxConnLifetime, idleTimeout, true)

// Disconnect at end
defer Disconnect()

// Set the key/value
_ = Set("example-expire", "my-value", "another-key")

// Set the expire
_ = Expire("example-expire", 1*time.Minute)
fmt.Print("expiration set")
Output:
expiration set

func Get

func Get(key string) (string, error)

Get gets a key from redis

Example

ExampleGet is an example of Get() method

// Create a local connection
_ = Connect(connectionURL, maxActiveConnections, maxIdleConnections, maxConnLifetime, idleTimeout, true)

// Disconnect at end
defer Disconnect()

// Set the key/value
_ = Set("example-get", "my-value", "another-key")

// Get the value
value, _ := Get("example-get")
fmt.Print(value)
Output:
my-value

func GetAllKeys

func GetAllKeys() (keys []string, err error)

GetAllKeys returns a []string of keys

Example

ExampleGetAllKeys is an example of GetAllKeys() method

// Create a local connection
_ = Connect(connectionURL, maxActiveConnections, maxIdleConnections, maxConnLifetime, idleTimeout, true)

// Disconnect at end
defer Disconnect()

// Set the key/value
_ = Set("example-get-all-keys", "my-value", "another-key")

// Get the value
_, _ = GetAllKeys()
fmt.Print("found keys")
Output:
found keys

func GetBytes

func GetBytes(key string) ([]byte, error)

GetBytes gets a key from redis in bytes

Example

ExampleGetBytes is an example of GetBytes() method

// Create a local connection
_ = Connect(connectionURL, maxActiveConnections, maxIdleConnections, maxConnLifetime, idleTimeout, true)

// Disconnect at end
defer Disconnect()

// Set the key/value
_ = Set("example-get-bytes", "my-value", "another-key")

// Get the value
value, _ := GetBytes("example-get-bytes")
fmt.Print(string(value))
Output:
my-value

func GetConnection

func GetConnection() redis.Conn

GetConnection will return a connection from the pool. The connection must be closed when done with use to return it to the pool

Example

ExampleGetConnection is an example of GetConnection() method

// Create a local connection
_ = Connect(connectionURL, maxActiveConnections, maxIdleConnections, maxConnLifetime, idleTimeout, true)

// Disconnect at end
defer Disconnect()

// Connected
_ = GetConnection()
fmt.Print("got connection")
Output:
got connection

func GetList added in v0.1.6

func GetList(key string) (list []string, err error)

GetList returns a []string stored in redis list

func GetPool

func GetPool() *redis.Pool

GetPool returns the underlying connection pool

Example

ExampleGetPool is an example of GetPool() method

// Create a local connection
_ = Connect(connectionURL, maxActiveConnections, maxIdleConnections, maxConnLifetime, idleTimeout, true)

// Disconnect at end
defer Disconnect()

// Get pool
_ = GetPool()
fmt.Print("got pool")
Output:
got pool

func HashGet

func HashGet(hash, key string) (string, error)

HashGet gets a key from redis via hash

Example

ExampleHashGet is an example of HashGet() method

// Create a local connection
_ = Connect(connectionURL, maxActiveConnections, maxIdleConnections, maxConnLifetime, idleTimeout, true)

// Disconnect at end
defer Disconnect()

// Set the key/value
_ = HashSet("example-hash-get", "test-hash-key", "my-cache-value")

// Get the value
val, _ := HashGet("example-hash-get", "test-hash-key")
fmt.Print(val)
Output:
my-cache-value

func HashMapGet

func HashMapGet(hashName string, keys ...interface{}) ([]string, error)

HashMapGet gets values from a hash map for corresponding keys

func HashMapSet

func HashMapSet(hashName string, pairs [][2]interface{}, dependencies ...string) (err error)

HashMapSet will set the hashKey to the value in the specified hashName and link a reference to each dependency for the entire hash

Example

ExampleHashMapSet is an example of HashMapSet() method

// Create a local connection
_ = Connect(connectionURL, maxActiveConnections, maxIdleConnections, maxConnLifetime, idleTimeout, true)

// Disconnect at end
defer Disconnect()

// Create pairs
pairs := [][2]interface{}{
	{"pair-1", "pair-1-value"},
	{"pair-2", "pair-2-value"},
	{"pair-3", "pair-3-value"},
}

// Set the hash map
_ = HashMapSet("example-hash-map-set", pairs, "test-hash-map-1", "test-hash-map-2")
fmt.Print("set complete")
Output:
set complete

func HashMapSetExp

func HashMapSetExp(hashName string, pairs [][2]interface{}, ttl time.Duration, dependencies ...string) (err error)

HashMapSetExp will set the hashKey to the value in the specified hashName and link a reference to each dependency for the entire hash

Example

ExampleHashMapSetExp is an example of HashMapSetExp() method

// Create a local connection
_ = Connect(connectionURL, maxActiveConnections, maxIdleConnections, maxConnLifetime, idleTimeout, true)

// Disconnect at end
defer Disconnect()

// Create pairs
pairs := [][2]interface{}{
	{"pair-1", "pair-1-value"},
	{"pair-2", "pair-2-value"},
	{"pair-3", "pair-3-value"},
}

// Set the hash map
_ = HashMapSetExp("example-hash-map-set-exp", pairs, 2*time.Minute, "test-hash-map-1", "test-hash-map-2")
fmt.Print("set complete")
Output:
set complete

func HashSet

func HashSet(hashName, hashKey string, value interface{}, dependencies ...string) (err error)

HashSet will set the hashKey to the value in the specified hashName and link a reference to each dependency for the entire hash

Example

ExampleHashSet is an example of HashSet() method

// Create a local connection
_ = Connect(connectionURL, maxActiveConnections, maxIdleConnections, maxConnLifetime, idleTimeout, true)

// Disconnect at end
defer Disconnect()

// Set the key/value
_ = HashSet("example-hash-set", "test-hash-key", "my-cache-value")
fmt.Print("set complete")
Output:
set complete

func KillByDependency

func KillByDependency(keys ...string) (total int, err error)

KillByDependency removes all keys which are listed as depending on the key(s) Also: Delete()

Example

ExampleKillByDependency is an example of KillByDependency() method

// Create a local connection
_ = Connect(connectionURL, maxActiveConnections, maxIdleConnections, maxConnLifetime, idleTimeout, true)

// Disconnect at end
defer Disconnect()

// Set the key/value
_ = Set("example-destroy-cache", "my-value", "another-key")

// Delete keys
_, _ = KillByDependency("another-key", "another-key-2")
fmt.Print("deleted keys")
Output:
deleted keys

func RegisterScript

func RegisterScript(script string) (sha string, err error)

RegisterScript register a script

Example

ExampleRegisterScript is an example of RegisterScript() method

// Create a local connection
_ = Connect(connectionURL, maxActiveConnections, maxIdleConnections, maxConnLifetime, idleTimeout, true)

// Disconnect at end
defer Disconnect()

// Fire the method
sha, _ := RegisterScript(killByDependencyLua)
fmt.Print(sha)
Output:
a648f768f57e73e2497ccaa113d5ad9e731c5cd8

func RegisterScripts

func RegisterScripts() (err error)

RegisterScripts register all scripts

Example

ExampleRegisterScripts is an example of RegisterScripts() method

// Create a local connection
_ = Connect(connectionURL, maxActiveConnections, maxIdleConnections, maxConnLifetime, idleTimeout, true)

// Disconnect at end
defer Disconnect()

// Fire
_ = RegisterScripts()
fmt.Print("registered")
Output:
registered

func ReleaseLock added in v0.1.2

func ReleaseLock(name, secret string) (released bool, err error)

ReleaseLock releases the redis lock

func Set

func Set(key string, value interface{}, dependencies ...string) (err error)

Set will set the key in redis and keep a reference to each dependency value can be both a string or []byte

Example

ExampleSet is an example of Set() method

// Create a local connection
_ = Connect(connectionURL, maxActiveConnections, maxIdleConnections, maxConnLifetime, idleTimeout, true)

// Disconnect at end
defer Disconnect()

// Set the key/value
_ = Set("example-set", "my-value", "another-key")
fmt.Print("set complete")
Output:
set complete

func SetAdd

func SetAdd(setName, member interface{}, dependencies ...string) (err error)

SetAdd will add the member to the Set and link a reference to each dependency for the entire Set

func SetAddMany added in v0.0.9

func SetAddMany(setName string, members ...interface{}) (err error)

SetAddMany will add many values to an existing set

func SetExp

func SetExp(key string, value interface{}, ttl time.Duration, dependencies ...string) (err error)

SetExp will set the key in redis and keep a reference to each dependency value can be both a string or []byte

Example

ExampleSetExp is an example of SetExp() method

// Create a local connection
_ = Connect(connectionURL, maxActiveConnections, maxIdleConnections, maxConnLifetime, idleTimeout, true)

// Disconnect at end
defer Disconnect()

// Set the key/value
_ = SetExp("example-set-exp", "my-value", 2*time.Minute, "another-key")
fmt.Print("set complete")
Output:
set complete

func SetIsMember

func SetIsMember(set, member interface{}) (bool, error)

SetIsMember returns if the member is part of the set

func SetList added in v0.1.6

func SetList(key string, slice []string) (err error)

SetList saves a slice as a redis list (appends)

func SetRemoveMember

func SetRemoveMember(set, member interface{}) (err error)

SetRemoveMember removes the member from the set

func WriteLock added in v0.1.2

func WriteLock(name, secret string, ttl int64) (locked bool, err error)

WriteLock attempts to grab a redis lock.

Types

This section is empty.

Directories

Path Synopsis
Package main is an example package using the cache package
Package main is an example package using the cache package

Jump to

Keyboard shortcuts

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