Convert Figma logo to code with AI

redis logogo-redis

Redis Go client

19,869
2,338
19,869
245

Top Related Projects

19,865

Redis Go client

9,738

Go client for Redis

2,330

A fast Golang Redis client that supports Client Side Caching, Auto Pipelining, Generics OM, RedisJSON, RedisBloom, RediSearch, etc.

Quick Overview

Go-redis is a popular Redis client for Go, offering a comprehensive set of features for interacting with Redis databases. It provides a type-safe API, supports Redis Cluster, Sentinel, and various other Redis features, making it a robust choice for Go developers working with Redis.

Pros

  • Extensive feature support, including Redis Cluster, Sentinel, and Pub/Sub
  • Type-safe API with support for custom types and structs
  • Active development and maintenance with frequent updates
  • Comprehensive documentation and examples

Cons

  • Learning curve for advanced features and configurations
  • Performance overhead compared to lower-level clients in some scenarios
  • Dependency on external libraries for certain functionalities
  • Limited support for older Redis versions

Code Examples

  1. Basic connection and key-value operations:
import "github.com/redis/go-redis/v9"

rdb := redis.NewClient(&redis.Options{
    Addr: "localhost:6379",
})

err := rdb.Set(ctx, "key", "value", 0).Err()
if err != nil {
    panic(err)
}

val, err := rdb.Get(ctx, "key").Result()
if err != nil {
    panic(err)
}
fmt.Println("key", val)
  1. Using Redis Pipelines for batch operations:
pipe := rdb.Pipeline()

incr := pipe.Incr(ctx, "pipeline_counter")
pipe.Expire(ctx, "pipeline_counter", time.Hour)

_, err := pipe.Exec(ctx)
if err != nil {
    panic(err)
}

fmt.Println(incr.Val())
  1. Working with Redis Pub/Sub:
pubsub := rdb.Subscribe(ctx, "mychannel")
defer pubsub.Close()

ch := pubsub.Channel()

go func() {
    for msg := range ch {
        fmt.Println(msg.Channel, msg.Payload)
    }
}()

err := rdb.Publish(ctx, "mychannel", "hello").Err()
if err != nil {
    panic(err)
}

Getting Started

To start using go-redis, first install it using:

go get github.com/redis/go-redis/v9

Then, import it in your Go code:

import "github.com/redis/go-redis/v9"

Create a new Redis client:

rdb := redis.NewClient(&redis.Options{
    Addr: "localhost:6379",
    Password: "", // no password set
    DB: 0,  // use default DB
})

Now you can use rdb to interact with your Redis database using the various methods provided by go-redis.

Competitor Comparisons

19,865

Redis Go client

Pros of go-redis

  • More actively maintained with frequent updates
  • Extensive feature set including support for Redis Cluster and Sentinel
  • Comprehensive documentation and examples

Cons of go-redis

  • Slightly more complex API due to additional features
  • May have a steeper learning curve for beginners

Code Comparison

go-redis:

client := redis.NewClient(&redis.Options{
    Addr: "localhost:6379",
})

err := client.Set("key", "value", 0).Err()
val, err := client.Get("key").Result()

go-redis:

client := redis.NewClient(&redis.Options{
    Addr: "localhost:6379",
})

err := client.Set("key", "value", 0).Err()
val, err := client.Get("key").Result()

Summary

Both go-redis and go-redis are popular Redis client libraries for Go. The code comparison shows that their basic usage is identical, which is not surprising as they are the same project. The pros and cons listed for go-redis are in comparison to other Redis client libraries for Go, as there is no actual difference between the two repositories mentioned in the prompt.

In reality, redis/go-redis is the official repository for the go-redis project. It's likely that the comparison request was meant to be between go-redis and another Redis client library for Go. For an accurate comparison, it would be necessary to specify a different library to compare against go-redis.

9,738

Go client for Redis

Pros of Redigo

  • Lower-level API offering more control and flexibility
  • Smaller memory footprint and potentially better performance
  • Simpler codebase, easier to understand and contribute to

Cons of Redigo

  • Less feature-rich compared to go-redis
  • Requires more manual handling of connections and pooling
  • Less active development and community support

Code Comparison

Redigo:

conn, err := redis.Dial("tcp", "localhost:6379")
if err != nil {
    // handle error
}
defer conn.Close()

_, err = conn.Do("SET", "key", "value")

go-redis:

client := redis.NewClient(&redis.Options{
    Addr: "localhost:6379",
})

err := client.Set("key", "value", 0).Err()
if err != nil {
    // handle error
}

Both Redigo and go-redis are popular Redis clients for Go, each with its own strengths. Redigo provides a lower-level API, giving developers more control over Redis operations and potentially better performance. However, go-redis offers a more feature-rich and user-friendly experience with built-in connection pooling and higher-level abstractions.

The choice between the two depends on specific project requirements, desired level of control, and developer preferences. go-redis might be more suitable for projects needing a quick setup and extensive features, while Redigo could be preferable for applications requiring fine-grained control over Redis operations.

2,330

A fast Golang Redis client that supports Client Side Caching, Auto Pipelining, Generics OM, RedisJSON, RedisBloom, RediSearch, etc.

Pros of rueidis

  • Improved performance with lower CPU and memory usage
  • Built-in support for Redis Cluster and Redis Sentinel
  • Automatic pipelining for better network efficiency

Cons of rueidis

  • Less mature and potentially less stable than go-redis
  • Smaller community and fewer third-party integrations
  • Steeper learning curve due to different API design

Code Comparison

go-redis:

client := redis.NewClient(&redis.Options{
    Addr: "localhost:6379",
})
err := client.Set("key", "value", 0).Err()
val, err := client.Get("key").Result()

rueidis:

client, err := rueidis.NewClient(rueidis.ClientOption{
    InitAddress: []string{"127.0.0.1:6379"},
})
err = client.Do(ctx, client.B().Set().Key("key").Value("value").Build()).Error()
val, err := client.Do(ctx, client.B().Get().Key("key").Build()).ToString()

Both libraries provide Redis client functionality for Go, but rueidis focuses on performance optimizations and advanced Redis features. go-redis has a more traditional API and wider adoption, while rueidis offers potential performance benefits at the cost of a different programming model. The choice between them depends on specific project requirements and performance needs.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Redis client for Go

build workflow PkgGoDev Documentation codecov Chat

go-redis is brought to you by :star: uptrace/uptrace. Uptrace is an open-source APM tool that supports distributed tracing, metrics, and logs. You can use it to monitor applications and set up automatic alerts to receive notifications via email, Slack, Telegram, and others.

See OpenTelemetry example which demonstrates how you can use Uptrace to monitor go-redis.

How do I Redis?

Learn for free at Redis University

Build faster with the Redis Launchpad

Try the Redis Cloud

Dive in developer tutorials

Join the Redis community

Work at Redis

Documentation

Resources

Ecosystem

This client also works with Kvrocks, a distributed key value NoSQL database that uses RocksDB as storage engine and is compatible with Redis protocol.

Features

Installation

go-redis supports 2 last Go versions and requires a Go version with modules support. So make sure to initialize a Go module:

go mod init github.com/my/repo

Then install go-redis/v9:

go get github.com/redis/go-redis/v9

Quickstart

import (
    "context"
    "fmt"

    "github.com/redis/go-redis/v9"
)

var ctx = context.Background()

func ExampleClient() {
    rdb := redis.NewClient(&redis.Options{
        Addr:     "localhost:6379",
        Password: "", // no password set
        DB:       0,  // use default DB
    })

    err := rdb.Set(ctx, "key", "value", 0).Err()
    if err != nil {
        panic(err)
    }

    val, err := rdb.Get(ctx, "key").Result()
    if err != nil {
        panic(err)
    }
    fmt.Println("key", val)

    val2, err := rdb.Get(ctx, "key2").Result()
    if err == redis.Nil {
        fmt.Println("key2 does not exist")
    } else if err != nil {
        panic(err)
    } else {
        fmt.Println("key2", val2)
    }
    // Output: key value
    // key2 does not exist
}

The above can be modified to specify the version of the RESP protocol by adding the protocol option to the Options struct:

    rdb := redis.NewClient(&redis.Options{
        Addr:     "localhost:6379",
        Password: "", // no password set
        DB:       0,  // use default DB
        Protocol: 3, // specify 2 for RESP 2 or 3 for RESP 3
    })

Connecting via a redis url

go-redis also supports connecting via the redis uri specification. The example below demonstrates how the connection can easily be configured using a string, adhering to this specification.

import (
    "github.com/redis/go-redis/v9"
)

func ExampleClient() *redis.Client {
    url := "redis://user:password@localhost:6379/0?protocol=3"
    opts, err := redis.ParseURL(url)
    if err != nil {
        panic(err)
    }

    return redis.NewClient(opts)
}

Advanced Configuration

go-redis supports extending the client identification phase to allow projects to send their own custom client identification.

Default Client Identification

By default, go-redis automatically sends the client library name and version during the connection process. This feature is available in redis-server as of version 7.2. As a result, the command is "fire and forget", meaning it should fail silently, in the case that the redis server does not support this feature.

Disabling Identity Verification

When connection identity verification is not required or needs to be explicitly disabled, a DisableIndentity configuration option exists. In V10 of this library, DisableIndentity will become DisableIdentity in order to fix the associated typo.

To disable verification, set the DisableIndentity option to true in the Redis client options:

rdb := redis.NewClient(&redis.Options{
    Addr:            "localhost:6379",
    Password:        "",
    DB:              0,
    DisableIndentity: true, // Disable set-info on connect
})

Contributing

Please see out contributing guidelines to help us improve this library!

Look and feel

Some corner cases:

// SET key value EX 10 NX
set, err := rdb.SetNX(ctx, "key", "value", 10*time.Second).Result()

// SET key value keepttl NX
set, err := rdb.SetNX(ctx, "key", "value", redis.KeepTTL).Result()

// SORT list LIMIT 0 2 ASC
vals, err := rdb.Sort(ctx, "list", &redis.Sort{Offset: 0, Count: 2, Order: "ASC"}).Result()

// ZRANGEBYSCORE zset -inf +inf WITHSCORES LIMIT 0 2
vals, err := rdb.ZRangeByScoreWithScores(ctx, "zset", &redis.ZRangeBy{
    Min: "-inf",
    Max: "+inf",
    Offset: 0,
    Count: 2,
}).Result()

// ZINTERSTORE out 2 zset1 zset2 WEIGHTS 2 3 AGGREGATE SUM
vals, err := rdb.ZInterStore(ctx, "out", &redis.ZStore{
    Keys: []string{"zset1", "zset2"},
    Weights: []int64{2, 3}
}).Result()

// EVAL "return {KEYS[1],ARGV[1]}" 1 "key" "hello"
vals, err := rdb.Eval(ctx, "return {KEYS[1],ARGV[1]}", []string{"key"}, "hello").Result()

// custom command
res, err := rdb.Do(ctx, "set", "key", "value").Result()

Run the test

go-redis will start a redis-server and run the test cases.

The paths of redis-server bin file and redis config file are defined in main_test.go:

var (
	redisServerBin, _  = filepath.Abs(filepath.Join("testdata", "redis", "src", "redis-server"))
	redisServerConf, _ = filepath.Abs(filepath.Join("testdata", "redis", "redis.conf"))
)

For local testing, you can change the variables to refer to your local files, or create a soft link to the corresponding folder for redis-server and copy the config file to testdata/redis/:

ln -s /usr/bin/redis-server ./go-redis/testdata/redis/src
cp ./go-redis/testdata/redis.conf ./go-redis/testdata/redis/

Lastly, run:

go test

Another option is to run your specific tests with an already running redis. The example below, tests against a redis running on port 9999.:

REDIS_PORT=9999 go test <your options>

See also

Contributors

Thanks to all the people who already contributed!