cache

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 8, 2026 License: Apache-2.0 Imports: 14 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)
  • Sorted Sets (priority queues, leaderboards, ranked data)
  • Streams (append-only logs, event sourcing, time-series data)
  • Pub/Sub (real-time messaging with auto-reconnect)
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

All workflows are driven by modular configuration in .github/env/ — no YAML editing required.

View all workflows and the control center →

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.


Sorted Sets

Sorted sets store unique members each associated with a floating-point score. Ideal for priority queues, leaderboards, and ranked data.

Function Description
SortedSetAdd Add a single member with a score
SortedSetAddMany Add multiple members in one call
SortedSetRemove Remove a member
SortedSetRange Return members by index range (ascending)
SortedSetRangeWithScores Return members + scores by index range
SortedSetRangeByScore Return members within a score range
SortedSetRangeByScoreWithScores Return members + scores within a score range
SortedSetPopMin Atomically pop the lowest-score members
SortedSetCard Return the number of members
SortedSetScore Return the score of a specific member
// Priority queue: lower score = higher priority
_ = cache.SortedSetAdd(ctx, client, "jobs", 1, "urgent-task")
_ = cache.SortedSetAdd(ctx, client, "jobs", 5, "normal-task")
_ = cache.SortedSetAdd(ctx, client, "jobs", 10, "low-priority-task")

// Dequeue highest-priority item
popped, _ := cache.SortedSetPopMin(ctx, client, "jobs", 1)
fmt.Printf("processing: %s\n", popped[0].Member) // urgent-task

// Leaderboard: get top 3 with scores
members, _ := cache.SortedSetRangeWithScores(ctx, client, "leaderboard", 0, 2)
for _, m := range members {
    fmt.Printf("%s: %.0f pts\n", m.Member, m.Score)
}

Streams

Streams are append-only logs of key-value entries. Perfect for event sourcing, audit logs, and time-series data.

Function Description
StreamAdd Append an entry with an auto-generated ID
StreamAddCapped Append an entry and cap the stream length
StreamRead Read entries from a given ID (non-blocking)
StreamReadBlock Read entries, blocking until new data arrives
StreamTrim Trim the stream to a maximum number of entries
StreamLen Return the number of entries in the stream
// Append audit log entries
id, _ := cache.StreamAdd(ctx, client, "audit-log", map[string]string{
    "event": "user.login",
    "user":  "alice",
})
fmt.Printf("logged entry: %s\n", id)

// Read all entries from the beginning
entries, _ := cache.StreamRead(ctx, client, "audit-log", "0", 100)
for _, e := range entries {
    fmt.Printf("[%s] %v\n", e.ID, e.Fields)
}

// Keep stream bounded (drop oldest when over 1000 entries)
_, _ = cache.StreamAddCapped(ctx, client, "events", 1000, map[string]string{
    "type": "page.view",
    "path": "/home",
})

Pub/Sub

Pub/Sub enables real-time message delivery between producers and consumers. The Subscription type reconnects automatically on connection failure.

Function Description
Publish Send a message to a channel
Subscribe Subscribe to one or more channels by exact name
PSubscribe Subscribe to channels matching a glob pattern
(*Subscription).Close Unsubscribe and release resources
// Subscribe to a channel
sub, _ := cache.Subscribe(ctx, client, "notifications")

// Receive messages in a goroutine
go func() {
    for msg := range sub.Messages {
        fmt.Printf("[%s] %s\n", msg.Channel, string(msg.Data))
    }
}()

// Publish from anywhere
n, _ := cache.Publish(ctx, client, "notifications", "hello world")
fmt.Printf("delivered to %d subscriber(s)\n", n)

// Clean shutdown
_ = sub.Close()

Examples & Tests

All unit tests run via GitHub Actions and use Go version 1.25.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"
	SortedSetAddCommand      string = "ZADD"
	SortedSetCardCommand     string = "ZCARD"
	SortedSetPopMinCommand   string = "ZPOPMIN"
	SortedSetRangeByScoreCmd string = "ZRANGEBYSCORE"
	SortedSetRangeCommand    string = "ZRANGE"
	SortedSetRemCommand      string = "ZREM"
	SortedSetScoreCommand    string = "ZSCORE"
	StreamAddCommand         string = "XADD"
	StreamLenCommand         string = "XLEN"
	StreamReadCommand        string = "XREAD"
	StreamTrimCommand        string = "XTRIM"
	PublishCommand           string = "PUBLISH"
	SubscribeCommand         string = "SUBSCRIBE"
	PSubscribeCommand        string = "PSUBSCRIBE"
	UnsubscribeCommand       string = "UNSUBSCRIBE"
)

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 Publish added in v1.1.0

func Publish(ctx context.Context, client *Client, channel string, message interface{}) (int64, error)

Publish sends a message to the given channel. Returns the number of subscribers that received the message. Creates a new connection and closes connection at end of function call.

Custom connections use method: PublishRaw()

func PublishRaw added in v1.1.0

func PublishRaw(conn redis.Conn, channel string, message interface{}) (int64, error)

PublishRaw sends a message to the given channel. Returns the number of subscribers that received the message. Uses existing connection (does not close connection).

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

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 SortedSetAdd added in v1.1.0

func SortedSetAdd(ctx context.Context, client *Client, key string, score float64, member interface{}) error

SortedSetAdd adds a single member with a score to a sorted set Creates a new connection and closes connection at end of function call

Custom connections use method: SortedSetAddRaw()

Example

ExampleSortedSetAdd is an example of the method SortedSetAdd()

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

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

// Set the key/value
_ = SortedSetAdd(context.Background(), client, testKey, 1.0, testStringValue)
fmt.Printf("added member: %v", testStringValue)
Output:

added member: test-string-value

func SortedSetAddMany added in v1.1.0

func SortedSetAddMany(ctx context.Context, client *Client, key string, members ...SortedSetMember) error

SortedSetAddMany adds multiple members with scores to a sorted set Creates a new connection and closes connection at end of function call

Custom connections use method: SortedSetAddManyRaw()

func SortedSetAddManyRaw added in v1.1.0

func SortedSetAddManyRaw(conn redis.Conn, key string, members ...SortedSetMember) (err error)

SortedSetAddManyRaw adds multiple members with scores to a sorted set Uses existing connection (does not close connection)

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

func SortedSetAddRaw added in v1.1.0

func SortedSetAddRaw(conn redis.Conn, key string, score float64, member interface{}) (err error)

SortedSetAddRaw adds a single member with a score to a sorted set Uses existing connection (does not close connection)

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

func SortedSetCard added in v1.1.0

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

SortedSetCard returns the number of members in a sorted set Creates a new connection and closes connection at end of function call

Custom connections use method: SortedSetCardRaw()

func SortedSetCardRaw added in v1.1.0

func SortedSetCardRaw(conn redis.Conn, key string) (int64, error)

SortedSetCardRaw returns the number of members in a sorted set Uses existing connection (does not close connection)

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

func SortedSetRange added in v1.1.0

func SortedSetRange(ctx context.Context, client *Client, key string, start, stop int64) ([]string, error)

SortedSetRange returns the specified range of members in a sorted set (by index) Results are ordered from lowest to highest score Creates a new connection and closes connection at end of function call

Custom connections use method: SortedSetRangeRaw()

func SortedSetRangeByScore added in v1.1.0

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

SortedSetRangeByScore returns all members in a sorted set with scores between minScore and maxScore minScore and maxScore are string representations (e.g. "-inf", "+inf", "1.5") Creates a new connection and closes connection at end of function call

Custom connections use method: SortedSetRangeByScoreRaw()

func SortedSetRangeByScoreRaw added in v1.1.0

func SortedSetRangeByScoreRaw(conn redis.Conn, key, minScore, maxScore string) ([]string, error)

SortedSetRangeByScoreRaw returns all members in a sorted set with scores between minScore and maxScore Uses existing connection (does not close connection)

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

func SortedSetRangeRaw added in v1.1.0

func SortedSetRangeRaw(conn redis.Conn, key string, start, stop int64) ([]string, error)

SortedSetRangeRaw returns the specified range of members in a sorted set (by index) Uses existing connection (does not close connection)

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

func SortedSetRemove added in v1.1.0

func SortedSetRemove(ctx context.Context, client *Client, key string, member interface{}) error

SortedSetRemove removes a member from a sorted set Creates a new connection and closes connection at end of function call

Custom connections use method: SortedSetRemoveRaw()

func SortedSetRemoveRaw added in v1.1.0

func SortedSetRemoveRaw(conn redis.Conn, key string, member interface{}) (err error)

SortedSetRemoveRaw removes a member from a sorted set Uses existing connection (does not close connection)

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

func SortedSetScore added in v1.1.0

func SortedSetScore(ctx context.Context, client *Client, key string, member interface{}) (float64, bool, error)

SortedSetScore returns the score of a member in a sorted set Returns (score, true, nil) when found, (0, false, nil) when not found Creates a new connection and closes connection at end of function call

Custom connections use method: SortedSetScoreRaw()

func SortedSetScoreRaw added in v1.1.0

func SortedSetScoreRaw(conn redis.Conn, key string, member interface{}) (float64, bool, error)

SortedSetScoreRaw returns the score of a member in a sorted set Returns (score, true, nil) when found, (0, false, nil) when not found Uses existing connection (does not close connection)

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

func StreamAdd added in v1.1.0

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

StreamAdd appends an entry with an auto-generated ID to a stream Creates a new connection and closes connection at end of function call

Custom connections use method: StreamAddRaw()

Example

ExampleStreamAdd is an example of the method StreamAdd()

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

conn.Command(StreamAddCommand, testKey, "*", "field", "value").Expect([]byte("1-0"))

// Add an entry
id, _ := StreamAdd(context.Background(), client, testKey, map[string]string{"field": "value"})
fmt.Printf("added stream entry: %v", id)
Output:

added stream entry: 1-0

func StreamAddCapped added in v1.1.0

func StreamAddCapped(ctx context.Context, client *Client, key string, maxLen int64, fields map[string]string) (string, error)

StreamAddCapped appends an entry to a stream, trimming it to at most maxLen entries Creates a new connection and closes connection at end of function call

Custom connections use method: StreamAddCappedRaw()

func StreamAddCappedRaw added in v1.1.0

func StreamAddCappedRaw(conn redis.Conn, key string, maxLen int64, fields map[string]string) (string, error)

StreamAddCappedRaw appends an entry to a stream, trimming it to at most maxLen entries Uses existing connection (does not close connection)

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

func StreamAddRaw added in v1.1.0

func StreamAddRaw(conn redis.Conn, key string, fields map[string]string) (string, error)

StreamAddRaw appends an entry with an auto-generated ID to a stream Uses existing connection (does not close connection)

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

func StreamLen added in v1.1.0

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

StreamLen returns the number of entries in a stream Creates a new connection and closes connection at end of function call

Custom connections use method: StreamLenRaw()

func StreamLenRaw added in v1.1.0

func StreamLenRaw(conn redis.Conn, key string) (int64, error)

StreamLenRaw returns the number of entries in a stream Uses existing connection (does not close connection)

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

func StreamTrim added in v1.1.0

func StreamTrim(ctx context.Context, client *Client, key string, maxLen int64) (int64, error)

StreamTrim trims the stream to at most maxLen entries, removing oldest entries first Returns the number of entries removed Creates a new connection and closes connection at end of function call

Custom connections use method: StreamTrimRaw()

func StreamTrimRaw added in v1.1.0

func StreamTrimRaw(conn redis.Conn, key string, maxLen int64) (int64, error)

StreamTrimRaw trims the stream to at most maxLen entries, removing oldest entries first Returns the number of entries removed Uses existing connection (does not close connection)

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

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

type Message added in v1.1.0

type Message struct {
	Channel string // Channel the message was published to
	Pattern string // Pattern that matched (only set for PSubscribe messages)
	Data    []byte // Payload
}

Message represents a pub/sub message received from a Redis channel

type SortedSetMember added in v1.1.0

type SortedSetMember struct {
	Member interface{}
	Score  float64
}

SortedSetMember represents a member of a sorted set with its associated score

func SortedSetPopMin added in v1.1.0

func SortedSetPopMin(ctx context.Context, client *Client, key string, count int64) ([]SortedSetMember, error)

SortedSetPopMin removes and returns the member with the lowest score from a sorted set Creates a new connection and closes connection at end of function call

Custom connections use method: SortedSetPopMinRaw()

func SortedSetPopMinRaw added in v1.1.0

func SortedSetPopMinRaw(conn redis.Conn, key string, count int64) ([]SortedSetMember, error)

SortedSetPopMinRaw removes and returns the member(s) with the lowest score(s) from a sorted set Uses existing connection (does not close connection)

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

func SortedSetRangeByScoreWithScores added in v1.1.0

func SortedSetRangeByScoreWithScores(ctx context.Context, client *Client, key, minScore, maxScore string) ([]SortedSetMember, error)

SortedSetRangeByScoreWithScores returns all members with scores in a sorted set between minScore and maxScore Creates a new connection and closes connection at end of function call

Custom connections use method: SortedSetRangeByScoreWithScoresRaw()

func SortedSetRangeByScoreWithScoresRaw added in v1.1.0

func SortedSetRangeByScoreWithScoresRaw(conn redis.Conn, key, minScore, maxScore string) ([]SortedSetMember, error)

SortedSetRangeByScoreWithScoresRaw returns all members with scores in a sorted set between minScore and maxScore Uses existing connection (does not close connection)

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

func SortedSetRangeWithScores added in v1.1.0

func SortedSetRangeWithScores(ctx context.Context, client *Client, key string, start, stop int64) ([]SortedSetMember, error)

SortedSetRangeWithScores returns the specified range of members with their scores in a sorted set Results are ordered from lowest to highest score Creates a new connection and closes connection at end of function call

Custom connections use method: SortedSetRangeWithScoresRaw()

func SortedSetRangeWithScoresRaw added in v1.1.0

func SortedSetRangeWithScoresRaw(conn redis.Conn, key string, start, stop int64) ([]SortedSetMember, error)

SortedSetRangeWithScoresRaw returns the specified range of members with their scores in a sorted set Uses existing connection (does not close connection)

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

type StreamEntry added in v1.1.0

type StreamEntry struct {
	ID     string
	Fields map[string]string
}

StreamEntry represents a single Redis stream entry with an ID and key-value fields

func StreamRead added in v1.1.0

func StreamRead(ctx context.Context, client *Client, key, startID string, count int64) ([]StreamEntry, error)

StreamRead reads entries from a stream starting at startID (non-blocking) Use "0" for startID to read from the beginning, or "$" for only new entries Creates a new connection and closes connection at end of function call

Custom connections use method: StreamReadRaw()

func StreamReadBlock added in v1.1.0

func StreamReadBlock(ctx context.Context, client *Client, key, startID string, count, blockMs int64) ([]StreamEntry, error)

StreamReadBlock reads entries from a stream, blocking until data is available or blockMs elapses Respects context cancellation via DoContext when supported, or by closing the connection. Use blockMs=0 to block indefinitely. Creates a new connection and closes connection at end of function call

Custom connections use method: StreamReadBlockRaw()

func StreamReadBlockRaw added in v1.1.0

func StreamReadBlockRaw(conn redis.Conn, key, startID string, count, blockMs int64) ([]StreamEntry, error)

StreamReadBlockRaw reads entries from a stream with blocking support Uses existing connection (does not close connection)

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

func StreamReadRaw added in v1.1.0

func StreamReadRaw(conn redis.Conn, key, startID string, count int64) ([]StreamEntry, error)

StreamReadRaw reads entries from a stream starting at startID (non-blocking) Uses existing connection (does not close connection)

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

type Subscription added in v1.1.0

type Subscription struct {
	Messages <-chan Message // Buffered (100) incoming messages; receive until closed
	// contains filtered or unexported fields
}

Subscription represents an active Redis pub/sub subscription. Messages are delivered on the Messages channel; call Close() to unsubscribe and release resources.

func PSubscribe added in v1.1.0

func PSubscribe(ctx context.Context, client *Client, patterns ...string) (*Subscription, error)

PSubscribe subscribes to one or more Redis patterns and returns a Subscription. The Subscription's Messages channel delivers incoming messages until Close() is called or the context is canceled. The subscription reconnects automatically on connection failure. Creates a dedicated connection (not from the pool command-cycle).

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

func Subscribe added in v1.1.0

func Subscribe(ctx context.Context, client *Client, channels ...string) (*Subscription, error)

Subscribe subscribes to one or more Redis channels and returns a Subscription. The Subscription's Messages channel delivers incoming messages until Close() is called or the context is canceled. The subscription reconnects automatically on connection failure. Creates a dedicated connection (not from the pool command-cycle).

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

func (*Subscription) Close added in v1.1.0

func (s *Subscription) Close() error

Close unsubscribes and releases all resources held by the Subscription. It is safe to call Close multiple times; subsequent calls are no-ops.

Close signals the readLoop goroutine to stop, waits for it to exit, and then closes the underlying connection. This ordering is critical: the pool connection's Close() implementation drains pending responses by calling Receive() internally. If the readLoop goroutine is still blocked in Receive() when conn.Close() is called, both goroutines compete on the same non-thread-safe connection, causing a deadlock. Waiting for the goroutine (via s.wg) before calling conn.Close() eliminates this race.

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.
pubsub command
Package main provides an example of how to use Redis pub/sub messaging using the go-cache library.
Package main provides an example of how to use Redis pub/sub messaging 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
sorted_set command
Package main provides an example of how to use sorted sets as a priority queue using the go-cache library.
Package main provides an example of how to use sorted sets as a priority queue using the go-cache library.
stream command
Package main provides an example of how to use Redis streams as an append-only log using the go-cache library.
Package main provides an example of how to use Redis streams as an append-only log using the go-cache library.
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