Simple cache dependency system on-top of the famous redigo package.
CI / CD Β Β
|
|
Β Β Β Β Quality Β Β
|
|
Security Β Β
|
|
Β Β Β Β Community Β Β
|
|
πΒ Installation
|
π§ͺΒ ExamplesΒ &Β Tests
|
πΒ Documentation
|
π€Β Contributing
|
π οΈΒ CodeΒ Standards
|
β‘Β Benchmarks
|
π€Β AIΒ Usage
|
βοΈΒ License
|
π₯Β Maintainers
|
go-cache requires a supported release of Go.
go get github.com/mrz1836/go-cacheView the generated documentation
- Redis and Valkey support (wire-compatible β same client, URL and config)
- TLS via
rediss:///valkeys://and AWS ElastiCache (RBAC/ACL username auth) - Options-based connection setup (
ConnectWithOptions) - 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:installLibrary Deployment
This project uses goreleaser for streamlined binary and library deployment to GitHub. To get started, install it via:
brew install goreleaserThe 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=masterThis process ensures consistent, repeatable releases with properly versioned artifacts and citation metadata.
Build Commands
View all build commands
magex helpGitHub Workflows
All workflows are driven by modular configuration in .github/env/ β no YAML editing required.
Updating Dependencies
To update all dependencies (Go modules, linters, and related tools), run:
magex deps:updateThis 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.
Valkey is a drop-in, wire-compatible fork of Redis, so this library talks to both engines with the same client, URL, and configuration β just point the URL at your instance. Supported URL schemes: redis://, rediss://, valkey://, valkeys:// (the s variants enable TLS).
Use ConnectWithOptions for full control over TLS and authentication. The older positional Connect remains for backward compatibility and simply forwards to it.
// Plaintext, local (Redis or Valkey)
client, err := cache.ConnectWithOptions(ctx, cache.PoolOptions{
URL: "redis://localhost:6379", // or valkey://localhost:6379
IdleConnections: 10,
})For ElastiCache (Redis OR Valkey) with in-transit encryption and RBAC, use a rediss:// URL and supply the ACL username/password. When a username is set, a two-arg AUTH username password is issued (required by ElastiCache RBAC). Leave TLSConfig.ServerName empty and it defaults to the endpoint host β the correct SNI for ElastiCache.
client, err := cache.ConnectWithOptions(ctx, cache.PoolOptions{
URL: "rediss://my-cluster.abc123.use1.cache.amazonaws.com:6379",
IdleConnections: 10,
Username: "app-user", // ElastiCache RBAC / Redis ACL user
Password: os.Getenv("REDIS_PASSWORD"),
TLSConfig: &tls.Config{MinVersion: tls.VersionTLS12}, // optional; TLS is on via rediss://
})Credentials may also be embedded in the URL (
rediss://user:pass@host:6379), but supplying them viaUsername/Passwordkeeps secrets out of logs and connection strings. Single-endpoint (cluster-mode-disabled) deployments are supported; sharded cluster mode is not yet implemented.
Container-backed tests (real Redis and Valkey) live behind the docker build tag and require a running Docker daemon. They use the local Docker CLI directly (via os/exec) β no container libraries, so no extra dependencies are added to the module:
go test -tags=docker ./...They skip automatically when Docker is unavailable, so normal go test / magex test runs stay fast and Docker-free.
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 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 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()All unit tests run via GitHub Actions and use Go version 1.26.x. View the configuration file.
Run all tests (fast):
magex testRun all tests with race detector (slower):
magex test:raceRun the Go benchmarks:
magex benchRead more about this Go project's code standards.
Read the AI Usage & Assistant Guidelines for details on how AI is used in this project and how to interact with AI assistants.
![]() |
|---|
| MrZ |
View the contributing guidelines and please follow the code of conduct.
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! π
