gparedis

package module
v0.1.6 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 9 Imported by: 1

README

GPARedis

A Redis adapter for the Go Persistence API (GPA), providing type-safe Redis operations with compile-time type safety using Go generics.

Features

  • Type-safe operations: All key-value operations are type-safe with compile-time checking
  • GPA compliance: Implements the Go Persistence API interfaces
  • Redis-specific features: TTL support, atomic operations, pattern matching
  • Batch operations: Support for multi-get, multi-set, and multi-delete operations
  • Flexible configuration: Support for connection URLs and individual parameters
  • Connection management: Built-in connection pooling and health checks

Installation

go get github.com/lemmego/gparedis

Quick Start

package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "github.com/lemmego/gpa"
    "github.com/lemmego/gparedis"
)

type User struct {
    ID   string `json:"id"`
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func main() {
    // Create Redis provider
    config := gpa.Config{
        Host:     "localhost",
        Port:     6379,
        Database: "0",
    }
    
    provider, err := gparedis.NewProvider(config)
    if err != nil {
        log.Fatal(err)
    }
    defer provider.Close()
    
    // Get type-safe repository
    userRepo := gparedis.GetRepository[User](provider)
    
    // Store a user
    user := &User{ID: "123", Name: "John Doe", Age: 30}
    if err := userRepo.Set(context.Background(), "user:123", user); err != nil {
        log.Fatal(err)
    }
    
    // Retrieve a user
    retrievedUser, err := userRepo.Get(context.Background(), "user:123")
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Printf("Retrieved user: %+v\n", retrievedUser)
}

Configuration

Using Connection URL
config := gpa.Config{
    ConnectionURL: "redis://username:password@localhost:6379/0",
}
Using Individual Parameters
config := gpa.Config{
    Host:     "localhost",
    Port:     6379,
    Username: "username",
    Password: "password",
    Database: "0",
}
Redis-specific Options
config := gpa.Config{
    Host: "localhost",
    Port: 6379,
    Options: map[string]interface{}{
        "redis": map[string]interface{}{
            "max_retries":     3,
            "pool_size":       10,
            "min_idle_conns":  5,
            "dial_timeout":    "5s",
            "read_timeout":    "3s",
            "write_timeout":   "3s",
            "pool_timeout":    "4s",
        },
    },
}

Supported Operations

Basic Key-Value Operations
  • Get(ctx, key) - Retrieve a value by key
  • Set(ctx, key, value) - Store a value
  • DeleteKey(ctx, key) - Delete a key
  • KeyExists(ctx, key) - Check if key exists
Batch Operations
  • MGet(ctx, keys) - Get multiple values
  • MSet(ctx, pairs) - Set multiple key-value pairs
  • MDelete(ctx, keys) - Delete multiple keys
TTL Operations
  • SetWithTTL(ctx, key, value, ttl) - Store with expiration
  • SetTTL(ctx, key, ttl) - Set TTL for existing key
  • GetTTL(ctx, key) - Get remaining TTL
  • RemoveTTL(ctx, key) - Remove TTL (make persistent)
Atomic Operations
  • Increment(ctx, key, delta) - Atomic increment
  • Decrement(ctx, key, delta) - Atomic decrement
Pattern Operations
  • Keys(ctx, pattern) - Get keys matching pattern
  • Scan(ctx, cursor, pattern, count) - Scan keys with cursor

Supported Features

  • TTL: Time-to-live support for keys
  • Atomic Operations: Atomic increment/decrement operations
  • Pub/Sub: Redis pub/sub capabilities
  • Streaming: Redis streams support
  • Transactions: Redis transaction support

Error Handling

The package converts Redis errors to GPA errors with proper error types:

  • ErrorTypeNotFound - Key not found
  • ErrorTypeSerialization - JSON serialization/deserialization errors
  • ErrorTypeDatabase - General Redis errors

License

MIT License - see LICENSE.md for details.

Documentation

Overview

Package gparedis provides a Redis adapter for the Go Persistence API (GPA)

Package gparedis provides a Redis adapter for the Go Persistence API (GPA)

Index

Constants

View Source
const DefaultRepositoryKeyPrefix = "gparedis:"

DefaultRepositoryKeyPrefix is used by repositories created through a Provider when no prefix is configured.

Variables

This section is empty.

Functions

func GetRepository

func GetRepository[T any](p *Provider) gpa.AdvancedKeyValueRepository[T]

GetRepository returns a type-safe repository for any entity type T This enables the unified provider API: userRepo := gparedis.GetRepository[User](provider)

func NewAdvancedKVRepository

func NewAdvancedKVRepository[T any](provider *Provider, client *redis.Client, keyPrefix string) gpa.AdvancedKeyValueRepository[T]

NewAdvancedKVRepository creates a new type-safe advanced Redis repository. This repository implements all KV capabilities with compile-time type safety.

Types

type Provider

type Provider struct {
	// contains filtered or unexported fields
}

Provider implements gpa.Provider and gpa.KeyValueProvider using Redis

func NewProvider

func NewProvider(config gpa.Config) (*Provider, error)

NewProvider creates a new Redis provider instance

func (*Provider) Client added in v0.1.1

func (p *Provider) Client() interface{}

Client returns the underlying Redis client instance

func (*Provider) Close

func (p *Provider) Close() error

Close closes the Redis connection

func (*Provider) Configure

func (p *Provider) Configure(config gpa.Config) error

Configure applies configuration to the provider

func (*Provider) Delete added in v0.1.1

func (p *Provider) Delete(ctx context.Context, key string) error

Delete removes a key

func (*Provider) Exists added in v0.1.1

func (p *Provider) Exists(ctx context.Context, key string) (bool, error)

Exists checks if a key exists

func (*Provider) Expire added in v0.1.1

func (p *Provider) Expire(ctx context.Context, key string, ttl time.Duration) error

Expire sets TTL for a key

func (*Provider) Get added in v0.1.1

func (p *Provider) Get(ctx context.Context, key string) (interface{}, error)

Get retrieves a value by key

func (*Provider) Health

func (p *Provider) Health() error

Health checks if the Redis connection is healthy

func (*Provider) Keys added in v0.1.1

func (p *Provider) Keys(ctx context.Context, pattern string) ([]string, error)

Keys returns all keys matching a pattern

func (*Provider) ProviderInfo

func (p *Provider) ProviderInfo() gpa.ProviderInfo

ProviderInfo returns information about the Redis provider

func (*Provider) Repository added in v0.1.4

func (p *Provider) Repository[T any]() gpa.BasicKeyValueRepository[T]

Repository creates a type-safe repository from this provider instance.

func (*Provider) Set added in v0.1.1

func (p *Provider) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error

Set stores a key-value pair with optional TTL

func (*Provider) SupportedFeatures

func (p *Provider) SupportedFeatures() []gpa.Feature

SupportedFeatures returns the features supported by Redis

func (*Provider) TTL added in v0.1.1

func (p *Provider) TTL(ctx context.Context, key string) (time.Duration, error)

TTL returns the remaining TTL for a key

type Repository

type Repository[T any] struct {
	// contains filtered or unexported fields
}

RepositoryG implements type-safe Redis operations using Go generics. Provides compile-time type safety for all key-value operations.

func NewRepository

func NewRepository[T any](provider *Provider, client *redis.Client, keyPrefix string) *Repository[T]

NewRepository creates a new generic Redis repository for type T. Example: userRepo := NewRepository[User](provider, client, "user:")

func (*Repository[T]) Close

func (r *Repository[T]) Close() error

Close closes the repository and releases any resources.

func (*Repository[T]) Count

func (r *Repository[T]) Count(ctx context.Context, opts ...gpa.QueryOption) (int64, error)

Count is not applicable for Redis key-value store

func (*Repository[T]) Create

func (r *Repository[T]) Create(ctx context.Context, entity *T) error

Create is not applicable for Redis key-value store

func (*Repository[T]) CreateBatch

func (r *Repository[T]) CreateBatch(ctx context.Context, entities []*T) error

CreateBatch is not applicable for Redis key-value store

func (*Repository[T]) Decrement

func (r *Repository[T]) Decrement(ctx context.Context, key string, delta int64) (int64, error)

Decrement atomically subtracts delta from a numeric value.

func (*Repository[T]) Delete

func (r *Repository[T]) Delete(ctx context.Context, id interface{}) error

Delete is not applicable for Redis key-value store - use DeleteKey instead

func (*Repository[T]) DeleteByCondition

func (r *Repository[T]) DeleteByCondition(ctx context.Context, condition gpa.Condition) error

DeleteByCondition is not applicable for Redis key-value store

func (*Repository[T]) DeleteKey

func (r *Repository[T]) DeleteKey(ctx context.Context, key string) error

DeleteKey removes a key-value pair.

func (*Repository[T]) Exists

func (r *Repository[T]) Exists(ctx context.Context, opts ...gpa.QueryOption) (bool, error)

Exists is not applicable for Redis key-value store - use KeyExists instead

func (*Repository[T]) Expire

func (r *Repository[T]) Expire(ctx context.Context, key string, ttl time.Duration) error

Expire sets or updates the TTL for an existing key.

func (*Repository[T]) FindAll

func (r *Repository[T]) FindAll(ctx context.Context, opts ...gpa.QueryOption) ([]*T, error)

FindAll is not applicable for Redis key-value store

func (*Repository[T]) FindByID

func (r *Repository[T]) FindByID(ctx context.Context, id interface{}) (*T, error)

FindByID is not applicable for Redis key-value store - use Get instead

func (*Repository[T]) Get

func (r *Repository[T]) Get(ctx context.Context, key string) (*T, error)

Get retrieves a value by key with compile-time type safety. Returns the value directly without requiring a destination parameter.

func (*Repository[T]) GetEntityInfo

func (r *Repository[T]) GetEntityInfo() (*gpa.EntityInfo, error)

GetEntityInfo returns basic entity information for Redis

func (*Repository[T]) GetTTL

func (r *Repository[T]) GetTTL(ctx context.Context, key string) (time.Duration, error)

GetTTL returns the remaining time-to-live for a key.

func (*Repository[T]) Increment

func (r *Repository[T]) Increment(ctx context.Context, key string, delta int64) (int64, error)

Increment atomically adds delta to a numeric value.

func (*Repository[T]) KeyExists

func (r *Repository[T]) KeyExists(ctx context.Context, key string) (bool, error)

KeyExists checks if a key exists in the store.

func (*Repository[T]) Keys

func (r *Repository[T]) Keys(ctx context.Context, pattern string) ([]string, error)

Keys returns all keys matching the given pattern.

func (*Repository[T]) MDelete

func (r *Repository[T]) MDelete(ctx context.Context, keys []string) (int64, error)

MDelete removes multiple keys in a single operation.

func (*Repository[T]) MGet

func (r *Repository[T]) MGet(ctx context.Context, keys []string) (map[string]*T, error)

MGet retrieves multiple values by their keys with compile-time type safety. Returns a slice of pointers to values.

func (*Repository[T]) MSet

func (r *Repository[T]) MSet(ctx context.Context, pairs map[string]*T) error

MSet stores multiple key-value pairs with compile-time type safety.

func (*Repository[T]) Query

func (r *Repository[T]) Query(ctx context.Context, opts ...gpa.QueryOption) ([]*T, error)

Query is not applicable for Redis key-value store

func (*Repository[T]) QueryOne

func (r *Repository[T]) QueryOne(ctx context.Context, opts ...gpa.QueryOption) (*T, error)

QueryOne is not applicable for Redis key-value store

func (*Repository[T]) RawExec

func (r *Repository[T]) RawExec(ctx context.Context, query string, args []interface{}) (gpa.Result, error)

RawExec is not applicable for Redis key-value store

func (*Repository[T]) RawQuery

func (r *Repository[T]) RawQuery(ctx context.Context, query string, args []interface{}) ([]*T, error)

RawQuery is not applicable for Redis key-value store

func (*Repository[T]) RemoveTTL

func (r *Repository[T]) RemoveTTL(ctx context.Context, key string) error

RemoveTTL removes the TTL from a key, making it persistent.

func (*Repository[T]) Scan

func (r *Repository[T]) Scan(ctx context.Context, cursor uint64, pattern string, count int64) ([]string, uint64, error)

Scan iterates through keys matching a pattern using cursor-based pagination.

func (*Repository[T]) Set

func (r *Repository[T]) Set(ctx context.Context, key string, value *T) error

Set stores a value with compile-time type safety. Accepts the value directly without interface{} conversion.

func (*Repository[T]) SetTTL

func (r *Repository[T]) SetTTL(ctx context.Context, key string, ttl time.Duration) error

SetTTL sets or updates the TTL for an existing key.

func (*Repository[T]) SetWithTTL

func (r *Repository[T]) SetWithTTL(ctx context.Context, key string, value *T, ttl time.Duration) error

SetWithTTL stores a value with an expiration time and compile-time type safety.

func (*Repository[T]) TTL

func (r *Repository[T]) TTL(ctx context.Context, key string) (time.Duration, error)

TTL returns the remaining time until the key expires.

func (*Repository[T]) Transaction

func (r *Repository[T]) Transaction(ctx context.Context, fn gpa.TransactionFunc[T]) error

Transaction is not applicable for Redis key-value store

func (*Repository[T]) Update

func (r *Repository[T]) Update(ctx context.Context, entity *T) error

Update is not applicable for Redis key-value store - use Set instead

func (*Repository[T]) UpdatePartial

func (r *Repository[T]) UpdatePartial(ctx context.Context, id interface{}, updates map[string]interface{}) error

UpdatePartial is not applicable for Redis key-value store

Jump to

Keyboard shortcuts

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