cache

package module
v1.0.6 Latest Latest
Warning

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

Go to latest
Published: Dec 19, 2025 License: Apache-2.0 Imports: 12 Imported by: 11

README ΒΆ

πŸ“‘Β Β go-cache

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


Release Go Version License


CI / CD Β Β  Build Last Commit Β Β Β Β  Quality Β Β  Go Report Coverage
Security Β Β  Scorecard Security Β Β Β Β  Community Β Β  Contributors Bitcoin


Project Navigation
πŸš€Β Installation πŸ§ͺΒ ExamplesΒ &Β Tests πŸ“šΒ Documentation
🀝 Contributing πŸ› οΈΒ CodeΒ Standards ⚑ Benchmarks
πŸ€–Β AIΒ Usage βš–οΈΒ License πŸ‘₯Β Maintainers

Installation

go-cache requires a supported release of Go.

go get github.com/mrz1836/go-cache

Documentation

View the generated documentation

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)
Development Setup (Getting Started)

Install MAGE-X build tool for development:

# Install MAGE-X for development and building
go install github.com/mrz1836/mage-x/cmd/magex@latest
magex update:install
Library Deployment

This project uses goreleaser for streamlined binary and library deployment to GitHub. To get started, install it via:

brew install goreleaser

The release process is defined in the .goreleaser.yml configuration file.

Then create and push a new Git tag using:

magex version:bump bump=patch push=true branch=master

This process ensures consistent, repeatable releases with properly versioned artifacts and citation metadata.

Build Commands

View all build commands

magex help
GitHub Workflows
πŸŽ›οΈ The Workflow Control Center

All GitHub Actions workflows in this repository are powered by configuration files: .env.base (default configuration) and optionally .env.custom (project-specific overrides) – your one-stop shop for tweaking CI/CD behavior without touching a single YAML file! 🎯

Configuration Files:

  • .env.base – Default configuration that works for most Go projects
  • .env.custom – Optional project-specific overrides

This magical file controls everything from:

  • πŸš€ Go version matrix (test on multiple versions or just one)
  • πŸƒ Runner selection (Ubuntu or macOS, your wallet decides)
  • πŸ”¬ Feature toggles (coverage, fuzzing, linting, race detection, benchmarks)
  • πŸ›‘οΈ Security tool versions (gitleaks, nancy, govulncheck)
  • πŸ€– Auto-merge behaviors (how aggressive should the bots be?)
  • 🏷️ PR management rules (size labels, auto-assignment, welcome messages)

Pro tip: Want to disable code coverage? Just add ENABLE_CODE_COVERAGE=false to your .env.custom to override the default in .env.base and push. No YAML archaeology required!


Workflow Name Description
auto-merge-on-approval.yml Automatically merges PRs after approval and all required checks, following strict rules.
codeql-analysis.yml Analyzes code for security vulnerabilities using GitHub CodeQL.
dependabot-auto-merge.yml Automatically merges Dependabot PRs that meet all requirements.
fortress.yml Runs the GoFortress security and testing workflow, including linting, testing, releasing, and vulnerability checks.
pull-request-management.yml Labels PRs by branch prefix, assigns a default user if none is assigned, and welcomes new contributors with a comment.
scorecard.yml Runs OpenSSF Scorecard to assess supply chain security.
stale.yml Warns about (and optionally closes) inactive issues and PRs on a schedule or manual trigger.
sync-labels.yml Keeps GitHub labels in sync with the declarative manifest at .github/labels.yml.
Updating Dependencies

To update all dependencies (Go modules, linters, and related tools), run:

magex deps:update

This command ensures all dependencies are brought up to date in a single step, including Go modules and any managed tools. It is the recommended way to keep your development environment and CI in sync with the latest versions.


Examples & Tests

All unit tests run via GitHub Actions and use Go version 1.24.x. View the configuration file.

Run all tests (fast):

magex test

Run all tests with race detector (slower):

magex test:race

Benchmarks

Run the Go benchmarks:

magex bench

Code Standards

Read more about this Go project's code standards.


πŸ€– AI Usage & Assistant Guidelines

Read the AI Usage & Assistant Guidelines for details on how AI is used in this project and how to interact with AI assistants.


Maintainers

MrZ
MrZ

Contributing

View the contributing guidelines and please 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 (
	ErrRedisPoolNil    = errors.New("redis pool is nil")
	ErrMissingRedisURL = errors.New("missing required parameter: redisURL")
)

Define static errors to avoid dynamic error creation

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
connect command
Package main provides an example of how to connect to a Redis server using the go-cache library.
Package main provides an example of how to connect to a Redis server using the go-cache library.
delete command
Package main provides an example of how to delete a key from a Redis server using the go-cache library.
Package main provides an example of how to delete a key from a Redis server using the go-cache library.
exists command
Package main provides an example of how to check if a key exists in a Redis cache using the go-cache library.
Package main provides an example of how to check if a key exists in a Redis cache using the go-cache library.
get command
Package main provides an example of how to get a value from a Redis cache using the go-cache library.
Package main provides an example of how to get a value from a Redis cache using the go-cache library.
locks command
Package main shows an example of how to create a lock using the go-cache library.
Package main shows an example of how to create a lock using the go-cache library.
set command
Package main shows how to set a value in the cache
Package main shows how to set a value in the cache
set_expire command
Package main shows how to set a value in the cache with an expiration time
Package main shows how to set a value in the cache with an expiration time
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