cache

package module
v0.9.7 Latest Latest
Warning

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

Go to latest
Published: Apr 1, 2024 License: Apache-2.0 Imports: 12 Imported by: 9

README

go-cache

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

Release Build Status Report codecov Go
Mergify Status Gitpod Ready-to-Code 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
  • Better Pool Management & Creation
  • Get Connection with Context
  • Cache Dependencies Between Keys (toggle functionality)
  • NewRelic automatic segment support
  • Test Coverage (mock redis & real redis)
  • Register Scripts
  • Helper Methods (Get, Set, HashGet, etc)
  • Basic Lock/Release (from bgentry lock.go)
  • Connect via URL (deprecated)
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
diff                 Show the git diff
generate             Runs the go generate command in the base of the repo
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 lint and ALL tests
test-ci              Runs all tests via CI (exports coverage)
test-ci-no-race      Runs all tests via CI (no race) (exports coverage)
test-ci-short        Runs unit tests via CI (exports coverage)
test-no-lint         Runs just tests
test-short           Runs vet, lint and tests (excludes integration tests)
test-unit            Runs tests and outputs 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 GitHub Actions and uses Go version 1.19.x. View the 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

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! 🚀

Stars


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

View Source
const (
	AddToSetCommand      string = "SADD"
	AllKeysCommand       string = "*"
	AuthCommand          string = "AUTH"
	DeleteCommand        string = "DEL"
	DependencyPrefix     string = "depend:"
	EvalCommand          string = "EVALSHA"
	ExecuteCommand       string = "EXEC"
	ExistsCommand        string = "EXISTS"
	ExpireCommand        string = "EXPIRE"
	FlushAllCommand      string = "FLUSHALL"
	GetCommand           string = "GET"
	HashGetCommand       string = "HGET"
	HashKeySetCommand    string = "HSET"
	HashMapGetCommand    string = "HMGET"
	HashMapSetCommand    string = "HMSET"
	IsMemberCommand      string = "SISMEMBER"
	KeysCommand          string = "KEYS"
	ListPushCommand      string = "RPUSH"
	ListRangeCommand     string = "LRANGE"
	LoadCommand          string = "LOAD"
	MembersCommand       string = "SMEMBERS"
	MultiCommand         string = "MULTI"
	PingCommand          string = "PING"
	RemoveMemberCommand  string = "SREM"
	ScriptCommand        string = "SCRIPT"
	SelectCommand        string = "SELECT"
	SetCommand           string = "SET"
	SetExpirationCommand string = "SETEX"
)

Package constants (commands)

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 deprecated

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

ConnectToURL connects via REDIS_URL and returns a single connection

Deprecated: use Connect() Preferred method is "Connect()" to create a pool Source: "github.com/soveran/redisurl" Format of URL: 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(ctx context.Context, client *Client, keys ...string) (total int, err error)

Delete is an alias for KillByDependency() Creates a new connection and closes connection at end of function call

Custom connections use method: DeleteRaw()

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(context.Background(), client, testDependantKey)
if conn != nil {
	fmt.Printf("all dependencies deleted")
}
Output:

all dependencies deleted

func DeleteRaw added in v0.4.0

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

DeleteRaw is an alias for KillByDependency() Uses existing connection (does not close connection)

func DeleteWithoutDependency added in v0.0.8

func DeleteWithoutDependency(ctx context.Context, client *Client, keys ...string) (int, error)

DeleteWithoutDependency will remove keys without using dependency script Creates a new connection and closes connection at end of function call

Custom connections use method: DeleteWithoutDependencyRaw()

Example

ExampleDeleteWithoutDependency is an example of the method DeleteWithoutDependency()

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

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

// Set the key/value
_ = Set(context.Background(), client, testKey, testStringValue)
_ = Set(context.Background(), client, testKey+"2", testStringValue)

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

deleted keys: 2

func DeleteWithoutDependencyRaw added in v0.4.0

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

DeleteWithoutDependencyRaw will remove keys without using dependency script Uses existing connection (does not close connection)

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

func DestroyCache

func DestroyCache(ctx context.Context, client *Client) error

DestroyCache will flush the entire redis server It only removes keys, not scripts Creates a new connection and closes connection at end of function call

Custom connections use method: DestroyCacheRaw()

Example

ExampleDestroyCache is an example of the method DestroyCache()

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

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

// Fire the command
_ = DestroyCache(context.Background(), client)
fmt.Print("cache destroyed")
Output:

cache destroyed

func DestroyCacheRaw added in v0.4.0

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

DestroyCacheRaw will flush the entire redis server It only removes keys, not scripts Uses existing connection (does not close connection)

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

func Exists

func Exists(ctx context.Context, client *Client, key string) (bool, error)

Exists checks if a key is present or not Creates a new connection and closes connection at end of function call

Custom connections use method: ExistsRaw()

Example

ExampleExists is an example of the method Exists()

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

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

// Set the key/value
_ = Set(context.Background(), client, testKey, testStringValue, testDependantKey)

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

key exists

func ExistsRaw added in v0.4.0

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

ExistsRaw checks if a key is present or not Uses existing connection (does not close connection)

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

func Expire

func Expire(ctx context.Context, client *Client, key string, duration time.Duration) error

Expire sets the expiration for a given key Creates a new connection and closes connection at end of function call

Custom connections use method: ExpireRaw()

Example

ExampleExpire is an example of the method Expire()

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

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

// Set the key/value
_ = Set(context.Background(), client, testKey, testStringValue, testDependantKey)

// Fire the command
_ = Expire(context.Background(), client, 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 ExpireRaw added in v0.4.0

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

ExpireRaw sets the expiration for a given key Uses existing connection (does not close connection)

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

func Get

func Get(ctx context.Context, client *Client, key string) (string, error)

Get gets a key from redis in string format Creates a new connection and closes connection at end of function call

Custom connections use method: GetRaw()

Example

ExampleGet is an example of the method Get()

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

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

// Set the key/value
_ = Set(context.Background(), client, testKey, testStringValue, testDependantKey)

// Get the value
_, _ = Get(context.Background(), client, testKey)
fmt.Printf("got value: %s", testStringValue)
Output:

got value: test-string-value

func GetAllKeys

func GetAllKeys(ctx context.Context, client *Client) (keys []string, err error)

GetAllKeys returns a []string of keys Creates a new connection and closes connection at end of function call

Custom connections use method: GetAllKeysRaw()

Example

ExampleGetAllKeys is an example of the method GetAllKeys()

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

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

// Set the key/value
_ = Set(context.Background(), client, testKey, testStringValue, testDependantKey)

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

found keys: 2

func GetAllKeysRaw added in v0.4.0

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

GetAllKeysRaw returns a []string of keys Uses existing connection (does not close connection)

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

func GetBytes

func GetBytes(ctx context.Context, client *Client, key string) ([]byte, error)

GetBytes gets a key from redis formatted in bytes Creates a new connection and closes connection at end of function call

Custom connections use method: GetBytesRaw()

Example

ExampleGetBytes is an example of the method GetBytes()

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

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

// Set the key/value
_ = Set(context.Background(), client, testKey, testStringValue, testDependantKey)

// Get the value
_, _ = GetBytes(context.Background(), client, testKey)
fmt.Printf("got value: %s", testStringValue)
Output:

got value: test-string-value

func GetBytesRaw added in v0.4.0

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

GetBytesRaw gets a key from redis formatted in bytes Uses existing connection (does not close connection)

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

func GetList added in v0.1.6

func GetList(ctx context.Context, client *Client, key string) ([]string, error)

GetList returns a []string stored in redis list Creates a new connection and closes connection at end of function call

Custom connections use method: GetListRaw()

Example

ExampleGetList is an example of the method GetList()

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

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

// Set the key/value
_ = SetList(context.Background(), client, testKey, []string{testStringValue})

// Fire the command
_, _ = GetList(context.Background(), client, testKey)
fmt.Printf("got list: %v", []string{testStringValue})
Output:

got list: [test-string-value]

func GetListRaw added in v0.4.0

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

GetListRaw returns a []string stored in redis list Uses existing connection (does not close connection)

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

func GetRaw added in v0.4.0

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

GetRaw gets a key from redis in string format Uses existing connection (does not close connection)

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

func HashGet

func HashGet(ctx context.Context, client *Client, hash, key string) (string, error)

HashGet gets a key from redis via hash Creates a new connection and closes connection at end of function call

Custom connections use method: HashGetRaw()

Example

ExampleHashGet is an example of the method HashGet()

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

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

// Set the key/value
_ = HashSet(context.Background(), client, testHashName, testKey, testStringValue, testDependantKey)

// Get the value
_, _ = HashGet(context.Background(), client, testHashName, testKey)
fmt.Printf("got value: %s", testStringValue)
Output:

got value: test-string-value

func HashGetRaw added in v0.4.0

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

HashGetRaw gets a key from redis via hash Uses existing connection (does not close connection)

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

func HashMapGet

func HashMapGet(ctx context.Context, client *Client, hashName string, keys ...interface{}) ([]string, error)

HashMapGet gets values from a hash map for corresponding keys Creates a new connection and closes connection at end of function call

Custom connections use method: HashMapGetRaw()

func HashMapGetRaw added in v0.4.0

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

HashMapGetRaw gets values from a hash map for corresponding keys Uses existing connection (does not close connection)

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

func HashMapSet

func HashMapSet(ctx context.Context, client *Client, 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 Creates a new connection and closes connection at end of function call

Custom connections use method: HashMapSetRaw()

Example

ExampleHashMapSet is an example of the method HashMapSet()

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

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

// 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(context.Background(), client, 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(ctx context.Context, client *Client, 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 Creates a new connection and closes connection at end of function call

Custom connections use method: HashMapSetExpRaw()

Example

ExampleHashMapSetExp is an example of the method HashMapSetExp()

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

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

// 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(context.Background(), client, 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 HashMapSetExpRaw added in v0.4.0

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

HashMapSetExpRaw will set the hashKey to the value in the specified hashName and link a reference to each dependency for the entire hash Uses existing connection (does not close connection)

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

func HashMapSetRaw added in v0.4.0

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

HashMapSetRaw will set the hashKey to the value in the specified hashName and link a reference to each dependency for the entire hash Uses existing connection (does not close connection)

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

func HashSet

func HashSet(ctx context.Context, client *Client, 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 Creates a new connection and closes connection at end of function call

Custom connections use method: HashSetRaw()

Example

ExampleHashSet is an example of the method HashSet()

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

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

// Set the key/value
_ = HashSet(context.Background(), client, 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 HashSetRaw added in v0.4.0

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

HashSetRaw will set the hashKey to the value in the specified hashName and link a reference to each dependency for the entire hash Uses existing connection (does not close connection)

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

func KillByDependency

func KillByDependency(ctx context.Context, client *Client, keys ...string) (int, error)

KillByDependency removes all keys which are listed as depending on the key(s) Alias: Delete() Creates a new connection and closes connection at end of function call

Custom connections use method: KillByDependencyRaw()

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, _ := loadMockRedis()

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

// Run command
_, _ = KillByDependency(context.Background(), client, testDependantKey)
fmt.Printf("all dependencies removed")
Output:

all dependencies removed

func KillByDependencyRaw added in v0.4.0

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

KillByDependencyRaw 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

func Ping added in v0.6.3

func Ping(ctx context.Context, client *Client) error

Ping is a basic Ping->Pong method to determine connection Creates a new connection and closes connection at end of function call

Uses methods: Ping()

Example

ExamplePing is an example of the method Ping()

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

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

// Fire the command
_ = Ping(context.Background(), client)
fmt.Printf("ping->pong")
Output:

ping->pong

func PingRaw added in v0.6.3

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

PingRaw is a basic Ping->Pong method to determine connection Uses existing connection (does not close connection)

Uses methods: Ping()

func RegisterScript

func RegisterScript(ctx context.Context, client *Client, script string) (string, error)

RegisterScript register a new script Creates a new connection and closes connection at end of function call

Custom connections use method: RegisterScriptRaw()

Example

ExampleRegisterScript is an example of the method RegisterScript()

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

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

// Register known scripts
_, _ = RegisterScript(context.Background(), client, killByDependencyLua)

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

registered: a648f768f57e73e2497ccaa113d5ad9e731c5cd8

func RegisterScriptRaw added in v0.4.0

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

RegisterScriptRaw register a new script Uses existing connection (does not close connection)

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

func ReleaseLock added in v0.1.2

func ReleaseLock(ctx context.Context, client *Client, name, secret string) (bool, error)

ReleaseLock releases the redis lock Creates a new connection and closes connection at end of function call

Custom connections use method: ReleaseLockRaw()

Example

ExampleReleaseLock is an example of the method ReleaseLock()

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

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

// Release a lock
_, _ = ReleaseLock(context.Background(), client, "test-lock", "test-secret")

fmt.Printf("lock released")
Output:

lock released

func ReleaseLockRaw added in v0.4.0

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

ReleaseLockRaw releases the redis lock Uses existing connection (does not close connection)

func Set

func Set(ctx context.Context, client *Client, 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 Creates a new connection and closes connection at end of function call

Custom connections use method: SetRaw()

Example

ExampleSet is an example of the method Set()

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

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

// Set the key/value
_ = Set(context.Background(), client, 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(ctx context.Context, client *Client, 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 Creates a new connection and closes connection at end of function call

Custom connections use method: SetAddRaw()

Example

ExampleSetAdd is an example of the method SetAdd()

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

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

// Set the key/value
_ = SetAdd(context.Background(), client, testKey, testStringValue, testDependantKey)

// Fire the command
_, _ = SetIsMember(context.Background(), client, testKey, testStringValue)
fmt.Printf("found member: %v", testStringValue)
Output:

found member: test-string-value

func SetAddMany added in v0.0.9

func SetAddMany(ctx context.Context, client *Client, setName string, members ...interface{}) error

SetAddMany will add many values to an existing set Creates a new connection and closes connection at end of function call

Custom connections use method: SetAddManyRaw()

Example

ExampleSetAddMany is an example of the method SetAddMany()

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

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

// Set the key/value
_ = SetAddMany(context.Background(), client, testKey, testStringValue, testStringValue+"2")

// Fire the command
_, _ = SetIsMember(context.Background(), client, testKey, testStringValue+"2")
fmt.Printf("found member: %v", testStringValue+"2")
Output:

found member: test-string-value2

func SetAddManyRaw added in v0.4.0

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

SetAddManyRaw will add many values to an existing set Uses existing connection (does not close connection)

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

func SetAddRaw added in v0.4.0

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

SetAddRaw will add the member to the Set and link a reference to each dependency for the entire Set Uses existing connection (does not close connection)

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

func SetExp

func SetExp(ctx context.Context, client *Client, 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 Creates a new connection and closes connection at end of function call

Custom connections use method: SetExpRaw()

Example

ExampleSetExp is an example of the method SetExp()

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

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

// Set the key/value
_ = SetExp(context.Background(), client, 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 SetExpRaw added in v0.4.0

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

SetExpRaw will set the key in redis and keep a reference to each dependency value can be both a string or []byte Uses existing connection (does not close connection)

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

func SetIsMember

func SetIsMember(ctx context.Context, client *Client, set, member interface{}) (bool, error)

SetIsMember returns if the member is part of the set Creates a new connection and closes connection at end of function call

Custom connections use method: SetIsMemberRaw()

Example

ExampleSetIsMember is an example of the method SetIsMember()

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

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

// Set the key/value
_ = SetAddMany(context.Background(), client, testKey, testStringValue, testStringValue+"2")

// Fire the command
_, _ = SetIsMember(context.Background(), client, testKey, testStringValue+"2")
fmt.Printf("found member: %v", testStringValue+"2")
Output:

found member: test-string-value2

func SetIsMemberRaw added in v0.4.0

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

SetIsMemberRaw returns if the member is part of the set Uses existing connection (does not close connection)

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

func SetList added in v0.1.6

func SetList(ctx context.Context, client *Client, key string, slice []string) error

SetList saves a slice as a redis list (appends) Creates a new connection and closes connection at end of function call

Custom connections use method: SetListRaw()

Example

ExampleSetList is an example of the method SetList()

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

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

// Set the key/value
_ = SetList(context.Background(), client, testKey, []string{testStringValue})

// Fire the command
_, _ = GetList(context.Background(), client, testKey)
fmt.Printf("got list: %v", []string{testStringValue})
Output:

got list: [test-string-value]

func SetListRaw added in v0.4.0

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

SetListRaw saves a slice as a redis list (appends) Uses existing connection (does not close connection)

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

func SetMembers added in v0.4.5

func SetMembers(ctx context.Context, client *Client, set interface{}) ([]string, error)

SetMembers will fetch all members in the list Creates a new connection and closes connection at end of function call

Custom connections use method: SetMembersRaw()

Example

ExampleSetMembers is an example of the method SetMembers()

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

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

// Set the key/value
_ = SetAddMany(context.Background(), client, testKey, testStringValue, testStringValue)

// Fire the command
_, _ = SetMembers(context.Background(), client, testKey)
fmt.Printf("found members: [%v]", testStringValue)
Output:

found members: [test-string-value]

func SetMembersRaw added in v0.4.5

func SetMembersRaw(conn redis.Conn, set interface{}) ([]string, error)

SetMembersRaw will fetch all members in the list Uses existing connection (does not close connection)

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

func SetRaw added in v0.4.0

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

SetRaw will set the key in redis and keep a reference to each dependency value can be both a string or []byte Uses existing connection (does not close connection)

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

func SetRemoveMember

func SetRemoveMember(ctx context.Context, client *Client, set, member interface{}) error

SetRemoveMember removes the member from the set Creates a new connection and closes connection at end of function call

Custom connections use method: SetRemoveMemberRaw()

Example

ExampleSetRemoveMember is an example of the method SetRemoveMember()

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

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

// Set the key/value
_ = SetAddMany(context.Background(), client, testKey, testStringValue, testStringValue+"2")

// Fire the command
_ = SetRemoveMember(context.Background(), client, testKey, testStringValue+"2")
fmt.Printf("removed member: %v", testStringValue+"2")
Output:

removed member: test-string-value2

func SetRemoveMemberRaw added in v0.4.0

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

SetRemoveMemberRaw removes the member from the set Uses existing connection (does not close connection)

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

func SetToJSON added in v0.4.1

func SetToJSON(ctx context.Context, client *Client, keyName string, modelData interface{},
	ttl time.Duration, dependencies ...string) error

SetToJSON stores the struct data (Struct->JSON) into redis under a key Creates a new connection and closes connection at end of function call

Custom connections use method: SetToJSONRaw()

func SetToJSONRaw added in v0.4.1

func SetToJSONRaw(conn redis.Conn, keyName string, modelData interface{},
	ttl time.Duration, dependencies ...string) (err error)

SetToJSONRaw stores the struct data (Struct->JSON) into redis under a key Uses existing connection (does not close connection)

Uses methods: SetExpRaw() or SetRaw()

func WriteLock added in v0.1.2

func WriteLock(ctx context.Context, client *Client, name, secret string, ttl int64) (bool, error)

WriteLock attempts to grab a redis lock Creates a new connection and closes connection at end of function call

Custom connections use method: WriteLockRaw()

Example

ExampleWriteLock is an example of the method WriteLock()

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

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

// Write a lock
_, _ = WriteLock(context.Background(), client, "test-lock", "test-secret", int64(10))

fmt.Printf("lock created")
Output:

lock created

func WriteLockRaw added in v0.4.0

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

WriteLockRaw attempts to grab a redis lock Uses existing connection (does not close connection)

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)
	Pool          nrredis.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(ctx context.Context, redisURL string,
	maxActiveConnections, idleConnections int,
	maxConnLifetime, idleTimeout time.Duration,
	dependencyMode, newRelicEnabled bool, options ...redis.DialOption) (client *Client, err error)

Connect creates a new connection pool connected to the specified url

Format of URL: redis://localhost:6379

Example

ExampleConnect is an example of the method Connect()

client, _ := Connect(
	context.Background(),
	testLocalConnectionURL,
	testMaxActiveConnections,
	testMaxIdleConnections,
	testMaxConnLifetime,
	testIdleTimeout,
	false,
	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 you're finished Deprecated: use GetConnectionWithContext()

Example

ExampleClient_GetConnection is an example of the method GetConnection()

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

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

got a connection

func (*Client) GetConnectionWithContext added in v0.6.0

func (c *Client) GetConnectionWithContext(ctx context.Context) (redis.Conn, error)

GetConnectionWithContext will return a connection from the pool. (convenience method) The connection must be closed when you're finished

Example

ExampleClient_GetConnectionWithContext is an example of the method GetConnectionWithContext()

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

conn, _ := client.GetConnectionWithContext(context.Background())
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(ctx context.Context) (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(context.Background())

fmt.Printf("scripts registered")
Output:

scripts registered

Directories

Path Synopsis
examples
get
set
Package nrredis is for integrating New Relic into Redis
Package nrredis is for integrating New Relic into Redis

Jump to

Keyboard shortcuts

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