cache

package module
v0.3.1 Latest Latest
Warning

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

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

README

go-cache

Simple cache dependency system on-top of the famous redigo package

Release Build Status Report codecov Go Sponsor Donate


Table of Contents


Installation

go-cache requires a supported release of Go and redis.

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

Documentation

View the generated documentation

GoDoc

Features
  • Cache Dependencies Between Keys (toggle functionality)
  • Connect via URL
  • Better Pool Management & Creation
  • Test Coverage (mock redis & real redis)
  • 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:

all                    Runs multiple commands
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 this help message
install                Install the application
install-go             Install the application (Using Native Go)
lint                   Run the golangci-lint application (install if not found)
release                Full production release (creates release in Github)
release                Runs common.release then runs godocs
release-snap           Test the full release (build binaries)
release-test           Full production test release (everything except deploy)
replace-version        Replaces the version in HTML/JS (pre-deploy)
tag                    Generate a new tag and push (tag version=0.0.0)
tag-remove             Remove a tag if found (tag-remove version=0.0.0)
tag-update             Update an existing tag to current commit (tag-update version=0.0.0)
test                   Runs vet, lint and ALL tests
test-short             Runs vet, lint and tests (excludes integration tests)
test-travis            Runs all tests via Travis (also exports coverage)
test-travis-short      Runs unit tests via Travis (also exports coverage)
uninstall              Uninstall the application (and remove files)
update-linter          Update the golangci-lint package (macOS only)
vet                    Run the Go vet application
Package Dependencies

Examples & Tests

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

Run all tests (including integration tests)

make test

Run tests (excluding integration tests)

make test-short

Benchmarks

Run the Go benchmarks:

make bench

Code Standards

Read more about this Go project's code standards.


Usage

View the examples


Maintainers

MrZ MrZ
MrZ kayleg

Contributing

View the contributing guidelines and follow the code of conduct.

How can I help?

All kinds of contributions are welcome 🙌! The most basic way to show your support is to star 🌟 the project, or to raise issues 💬. You can also support this project by becoming a sponsor on GitHub 👏 or by making a bitcoin donation to ensure this journey continues indefinitely! 🚀


License

License

Documentation

Overview

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

If you have any suggestions or comments, please feel free to open an issue on this GitHub repository!

By @MrZ1836

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 CloseConnection added in v0.3.0

func CloseConnection(conn redis.Conn) redis.Conn

CloseConnection will close a connection

func ConnectToURL

func ConnectToURL(connectToURL string, options ...redis.DialOption) (conn redis.Conn, err error)

ConnectToURL connects via REDIS_URL and returns a single connection Preferred method is Connect() to create a pool Source: github.com/soveran/redisurl URL Format: redis://localhost:6379

Example

ExampleConnectToURL is an example of the method ConnectToURL()

c, _ := ConnectToURL(testLocalConnectionURL)

// Close connections at end of request
defer CloseConnection(c)

fmt.Printf("connected")
Output:
connected

func Delete added in v0.0.2

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

Delete is an alias for KillByDependency()

Example

ExampleDelete is an example of the method Delete()

// Load a mocked redis for testing/examples
client, conn := loadMockRedis()

// Close connections at end of request
defer client.CloseAll(conn)

// Run command
_, _ = Delete(conn, testDependantKey)
if conn != nil {
	fmt.Printf("all dependencies deleted")
}
Output:
all dependencies deleted

func DeleteWithoutDependency added in v0.0.8

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

DeleteWithoutDependency will remove keys without using dependency script

Spec: https://redis.io/commands/del

Example

ExampleDeleteWithoutDependency is an example of the method DeleteWithoutDependency()

// Load a mocked redis for testing/examples
client, conn := loadMockRedis()

// Close connections at end of request
defer client.CloseAll(conn)

// Set the key/value
_ = Set(conn, testKey, testStringValue)
_ = Set(conn, testKey+"2", testStringValue)

// Delete keys
_, _ = DeleteWithoutDependency(conn, testKey, testKey+"2")
fmt.Printf("deleted keys: %d", 2)
Output:
deleted keys: 2

func DestroyCache

func DestroyCache(conn redis.Conn) (err error)

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

Spec: https://redis.io/commands/flushall

Example

ExampleDestroyCache is an example of the method DestroyCache()

// Load a mocked redis for testing/examples
client, conn := loadMockRedis()

// Close connections at end of request
defer client.CloseAll(conn)

// Fire the command
_ = DestroyCache(conn)
fmt.Print("cache destroyed")
Output:
cache destroyed

func Exists

func Exists(conn redis.Conn, key string) (bool, error)

Exists checks if a key is present or not

Spec: https://redis.io/commands/exists

Example

ExampleExists is an example of the method Exists()

// Load a mocked redis for testing/examples
client, conn := loadMockRedis()

// Close connections at end of request
defer client.CloseAll(conn)

// Set the key/value
_ = Set(conn, testKey, testStringValue, testDependantKey)

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

func Expire

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

Expire sets the expiration for a given key

Spec: https://redis.io/commands/expire

Example

ExampleExpire is an example of the method Expire()

// Load a mocked redis for testing/examples
client, conn := loadMockRedis()

// Close connections at end of request
defer client.CloseAll(conn)

// Set the key/value
_ = Set(conn, testKey, testStringValue, testDependantKey)

// Fire the command
_ = Expire(conn, testKey, 1*time.Minute)
fmt.Printf("expiration on key: %s set for: %v", testKey, 1*time.Minute)
Output:
expiration on key: test-key-name set for: 1m0s

func Get

func Get(conn redis.Conn, key string) (string, error)

Get gets a key from redis in string format

Spec: https://redis.io/commands/get

Example

ExampleGet is an example of the method Get()

// Load a mocked redis for testing/examples
client, conn := loadMockRedis()

// Close connections at end of request
defer client.CloseAll(conn)

// Set the key/value
_ = Set(conn, testKey, testStringValue, testDependantKey)

// Get the value
_, _ = Get(conn, testKey)
fmt.Printf("got value: %s", testStringValue)
Output:
got value: test-string-value

func GetAllKeys

func GetAllKeys(conn redis.Conn) (keys []string, err error)

GetAllKeys returns a []string of keys

Spec: https://redis.io/commands/keys

Example

ExampleGetAllKeys is an example of the method GetAllKeys()

// Load a mocked redis for testing/examples
client, conn := loadMockRedis()

// Close connections at end of request
defer client.CloseAll(conn)

// Set the key/value
_ = Set(conn, testKey, testStringValue, testDependantKey)

// Get the keys
_, _ = GetAllKeys(conn)
fmt.Printf("found keys: %d", len([]string{testKey, testDependantKey}))
Output:
found keys: 2

func GetBytes

func GetBytes(conn redis.Conn, key string) ([]byte, error)

GetBytes gets a key from redis formatted in bytes

Spec: https://redis.io/commands/get

Example

ExampleGetBytes is an example of the method GetBytes()

// Load a mocked redis for testing/examples
client, conn := loadMockRedis()

// Close connections at end of request
defer client.CloseAll(conn)

// Set the key/value
_ = Set(conn, testKey, testStringValue, testDependantKey)

// Get the value
_, _ = GetBytes(conn, testKey)
fmt.Printf("got value: %s", testStringValue)
Output:
got value: test-string-value

func GetList added in v0.1.6

func GetList(conn redis.Conn, key string) (list []string, err error)

GetList returns a []string stored in redis list

Spec: https://redis.io/commands/lrange

Example

ExampleGetList is an example of the method GetList()

// Load a mocked redis for testing/examples
client, conn := loadMockRedis()

// Close connections at end of request
defer client.CloseAll(conn)

// Set the key/value
_ = SetList(conn, testKey, []string{testStringValue})

// Fire the command
_, _ = GetList(conn, testKey)
fmt.Printf("got list: %v", []string{testStringValue})
Output:
got list: [test-string-value]

func HashGet

func HashGet(conn redis.Conn, hash, key string) (string, error)

HashGet gets a key from redis via hash

Spec: https://redis.io/commands/hget

Example

ExampleHashGet is an example of the method HashGet()

// Load a mocked redis for testing/examples
client, conn := loadMockRedis()

// Close connections at end of request
defer client.CloseAll(conn)

// Set the key/value
_ = HashSet(conn, testHashName, testKey, testStringValue, testDependantKey)

// Get the value
_, _ = HashGet(conn, testHashName, testKey)
fmt.Printf("got value: %s", testStringValue)
Output:
got value: test-string-value

func HashMapGet

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

HashMapGet gets values from a hash map for corresponding keys

Spec: https://redis.io/commands/hmget

func HashMapSet

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

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

Spec: https://redis.io/commands/hmset

Example

ExampleHashMapSet is an example of the method HashMapSet()

// Load a mocked redis for testing/examples
client, conn := loadMockRedis()

// Close connections at end of request
defer client.CloseAll(conn)

// 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(conn, testHashName, pairs, testDependantKey)
fmt.Printf("set: %s pairs: %d dep key: %s", testHashName, len(pairs), testDependantKey)
Output:
set: test-hash-name pairs: 3 dep key: test-dependant-key-name

func HashMapSetExp

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

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

Commands: https://redis.io/commands/hmset https://redis.io/commands/expire

Example

ExampleHashMapSetExp is an example of the method HashMapSetExp()

// Load a mocked redis for testing/examples
client, conn := loadMockRedis()

// Close connections at end of request
defer client.CloseAll(conn)

// 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(conn, testHashName, pairs, 5*time.Second, testDependantKey)
fmt.Printf("set: %s pairs: %d dep key: %s exp: %v", testHashName, len(pairs), testDependantKey, 5*time.Second)
Output:
set: test-hash-name pairs: 3 dep key: test-dependant-key-name exp: 5s

func HashSet

func HashSet(conn redis.Conn, hashName, hashKey string, value interface{}, dependencies ...string) error

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

Spec: https://redis.io/commands/hset

Example

ExampleHashSet is an example of the method HashSet()

// Load a mocked redis for testing/examples
client, conn := loadMockRedis()

// Close connections at end of request
defer client.CloseAll(conn)

// Set the key/value
_ = HashSet(conn, testHashName, testKey, testStringValue, testDependantKey)
fmt.Printf("set: %s:%s value: %s dep key: %s", testHashName, testKey, testStringValue, testDependantKey)
Output:
set: test-hash-name:test-key-name value: test-string-value dep key: test-dependant-key-name

func KillByDependency

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

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

Commands used: https://redis.io/commands/eval https://redis.io/commands/del

Example

ExampleKillByDependency is an example of the method KillByDependency()

// Load a mocked redis for testing/examples
client, conn := loadMockRedis()

// Close connections at end of request
defer client.CloseAll(conn)

// Run command
_, _ = KillByDependency(conn, testDependantKey)
if conn != nil {
	fmt.Printf("all dependencies removed")
}
Output:
all dependencies removed

func RegisterScript

func RegisterScript(client *Client, conn redis.Conn, script string) (sha string, err error)

RegisterScript register a new script

Spec: https://redis.io/commands/script-load

Example

ExampleRegisterScript is an example of the method RegisterScript()

// Load a mocked redis for testing/examples
client, conn := loadMockRedis()

// Close connections at end of request
defer client.CloseAll(conn)

// Register known scripts
_, _ = RegisterScript(client, conn, killByDependencyLua)

fmt.Printf("registered: %s", testKillDependencyHash)
Output:
registered: a648f768f57e73e2497ccaa113d5ad9e731c5cd8

func ReleaseLock added in v0.1.2

func ReleaseLock(conn redis.Conn, name, secret string) (bool, error)

ReleaseLock releases the redis lock

Example

ExampleReleaseLock is an example of the method ReleaseLock()

// Load a mocked redis for testing/examples
client, conn := loadMockRedis()

// Close connections at end of request
defer client.CloseAll(conn)

// Release a lock
_, _ = ReleaseLock(conn, "test-lock", "test-secret")

if conn != nil {
	fmt.Printf("lock released")
}
Output:
lock released

func Set

func Set(conn redis.Conn, key string, value interface{}, dependencies ...string) error

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

Spec: https://redis.io/commands/set

Example

ExampleSet is an example of the method Set()

// Load a mocked redis for testing/examples
client, conn := loadMockRedis()

// Close connections at end of request
defer client.CloseAll(conn)

// Set the key/value
_ = Set(conn, testKey, testStringValue, testDependantKey)
fmt.Printf("set: %s value: %s dep key: %s", testKey, testStringValue, testDependantKey)
Output:
set: test-key-name value: test-string-value dep key: test-dependant-key-name

func SetAdd

func SetAdd(conn redis.Conn, setName, member interface{}, dependencies ...string) error

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

Spec: https://redis.io/commands/sadd

Example

ExampleSetAdd is an example of the method SetAdd()

// Load a mocked redis for testing/examples
client, conn := loadMockRedis()

// Close connections at end of request
defer client.CloseAll(conn)

// Set the key/value
_ = SetAdd(conn, testKey, testStringValue, testDependantKey)

// Fire the command
_, _ = SetIsMember(conn, testKey, testStringValue)
fmt.Printf("found member: %v", testStringValue)
Output:
found member: test-string-value

func SetAddMany added in v0.0.9

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

SetAddMany will add many values to an existing set

Spec: https://redis.io/commands/sadd

Example

ExampleSetAddMany is an example of the method SetAddMany()

// Load a mocked redis for testing/examples
client, conn := loadMockRedis()

// Close connections at end of request
defer client.CloseAll(conn)

// Set the key/value
_ = SetAddMany(conn, testKey, testStringValue, testStringValue+"2")

// Fire the command
_, _ = SetIsMember(conn, testKey, testStringValue+"2")
fmt.Printf("found member: %v", testStringValue+"2")
Output:
found member: test-string-value2

func SetExp

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

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

Spec: https://redis.io/commands/setex

Example

ExampleSetExp is an example of the method SetExp()

// Load a mocked redis for testing/examples
client, conn := loadMockRedis()

// Close connections at end of request
defer client.CloseAll(conn)

// Set the key/value
_ = SetExp(conn, testKey, testStringValue, 2*time.Minute, testDependantKey)
fmt.Printf("set: %s value: %s exp: %v dep key: %s", testKey, testStringValue, 2*time.Minute, testDependantKey)
Output:
set: test-key-name value: test-string-value exp: 2m0s dep key: test-dependant-key-name

func SetIsMember

func SetIsMember(conn redis.Conn, set, member interface{}) (bool, error)

SetIsMember returns if the member is part of the set

Spec: https://redis.io/commands/sismember

Example

ExampleSetIsMember is an example of the method SetIsMember()

// Load a mocked redis for testing/examples
client, conn := loadMockRedis()

// Close connections at end of request
defer client.CloseAll(conn)

// Set the key/value
_ = SetAddMany(conn, testKey, testStringValue, testStringValue+"2")

// Fire the command
_, _ = SetIsMember(conn, testKey, testStringValue+"2")
fmt.Printf("found member: %v", testStringValue+"2")
Output:
found member: test-string-value2

func SetList added in v0.1.6

func SetList(conn redis.Conn, key string, slice []string) (err error)

SetList saves a slice as a redis list (appends)

Spec: https://redis.io/commands/rpush

Example

ExampleSetList is an example of the method SetList()

// Load a mocked redis for testing/examples
client, conn := loadMockRedis()

// Close connections at end of request
defer client.CloseAll(conn)

// Set the key/value
_ = SetList(conn, testKey, []string{testStringValue})

// Fire the command
_, _ = GetList(conn, testKey)
fmt.Printf("got list: %v", []string{testStringValue})
Output:
got list: [test-string-value]

func SetRemoveMember

func SetRemoveMember(conn redis.Conn, set, member interface{}) (err error)

SetRemoveMember removes the member from the set

Spec: https://redis.io/commands/srem

Example

ExampleSetRemoveMember is an example of the method SetRemoveMember()

// Load a mocked redis for testing/examples
client, conn := loadMockRedis()

// Close connections at end of request
defer client.CloseAll(conn)

// Set the key/value
_ = SetAddMany(conn, testKey, testStringValue, testStringValue+"2")

// Fire the command
_ = SetRemoveMember(conn, testKey, testStringValue+"2")
fmt.Printf("removed member: %v", testStringValue+"2")
Output:
removed member: test-string-value2

func WriteLock added in v0.1.2

func WriteLock(conn redis.Conn, name, secret string, ttl int64) (bool, error)

WriteLock attempts to grab a redis lock

Example

ExampleWriteLock is an example of the method WriteLock()

// Load a mocked redis for testing/examples
client, conn := loadMockRedis()

// Close connections at end of request
defer client.CloseAll(conn)

// Write a lock
_, _ = WriteLock(conn, "test-lock", "test-secret", int64(10))

if conn != nil {
	fmt.Printf("lock created")
}
Output:
lock created

Types

type Client added in v0.3.0

type Client struct {
	DependencyScriptSha string      // Stored SHA of the script after loaded
	Pool                *redis.Pool // Redis pool for the client (get connections)
	ScriptsLoaded       []string    // List of scripts that have been loaded
}

Client is used to store the redis.Pool and additional fields/information

func Connect

func Connect(redisURL string, maxActiveConnections, idleConnections, maxConnLifetime, idleTimeout int,
	dependencyMode bool, options ...redis.DialOption) (client *Client, err error)

Connect creates a new connection pool connected to the specified url URL Format: redis://localhost:6379

Example

ExampleConnect is an example of the method Connect()

client, _ := Connect(
	testLocalConnectionURL,
	testMaxActiveConnections,
	testMaxIdleConnections,
	testMaxConnLifetime,
	testIdleTimeout,
	false,
)

// Close connections at end of request
defer client.Close()

fmt.Printf("connected")
Output:
connected

func (*Client) Close added in v0.3.0

func (c *Client) Close()

Close closes the connection pool

Example

ExampleClient_Close is an example of the method Close()

// Load a mocked redis for testing/examples
client, _ := loadMockRedis()

// Close connections at end of request
defer client.Close()

fmt.Printf("closed the pool")
Output:
closed the pool

func (*Client) CloseAll added in v0.3.0

func (c *Client) CloseAll(conn redis.Conn) redis.Conn

CloseAll closes the connection pool and given connection

Example

ExampleClient_CloseAll is an example of the method CloseAll()

// Load a mocked redis for testing/examples
client, conn := loadMockRedis()

// Close connections at end of request
defer client.CloseAll(conn)

// Got a connection?
if conn != nil {
	fmt.Printf("got a connection and closed")
}
Output:
got a connection and closed

func (*Client) CloseConnection added in v0.3.0

func (c *Client) CloseConnection(conn redis.Conn) redis.Conn

CloseConnection will close a previously open connection

Example

ExampleClient_CloseConnection is an example of the method CloseConnection()

// Load a mocked redis for testing/examples
client, conn := loadMockRedis()

// Close after finished
defer client.CloseConnection(conn)

// Got a connection?
if conn != nil {
	fmt.Printf("got a connection and closed")
}
Output:
got a connection and closed

func (*Client) GetConnection added in v0.3.0

func (c *Client) GetConnection() redis.Conn

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

Example

ExampleClient_GetConnection is an example of the method GetConnection()

client, _ := Connect(
	testLocalConnectionURL,
	testMaxActiveConnections,
	testMaxIdleConnections,
	testMaxConnLifetime,
	testIdleTimeout,
	false,
)

conn := client.GetConnection()
defer client.CloseAll(conn)
if conn != nil {
	fmt.Printf("got a connection")
}
Output:
got a connection

func (*Client) RegisterScripts added in v0.3.0

func (c *Client) RegisterScripts() (err error)

RegisterScripts will register all required scripts for additional functionality This method runs on Connect()

Example

ExampleClient_RegisterScripts is an example of the method RegisterScripts()

// Load a mocked redis for testing/examples
client, conn := loadMockRedis()

// Close connections at end of request
defer client.CloseAll(conn)

// Register known scripts
_ = client.RegisterScripts()

fmt.Printf("scripts registered")
Output:
scripts registered

Directories

Path Synopsis
examples
connect command
delete command
exists command
get command
locks command
set command
set_expire command

Jump to

Keyboard shortcuts

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