Skip to content
mrz1836Public

About

πŸ“‘ Cache dependency management on-top of the famous redigo package

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

6 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

710 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

πŸ“‘Β Β go-cache

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


Release Go Version License


CI / CD Β Β  Build Last Commit Β Β Β Β  Quality Β Β  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

  • 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: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.


Connecting to Redis or Valkey

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,
})

AWS ElastiCache (TLS + RBAC / ACL)

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 via Username/Password keeps secrets out of logs and connection strings. Single-endpoint (cluster-mode-disabled) deployments are supported; sharded cluster mode is not yet implemented.

Local testing with real Redis/Valkey

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

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.26.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

About

πŸ“‘ Cache dependency management on-top of the famous redigo package

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

6 stars

Watchers

0 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages