项目作者: go-redis

项目描述 :
适用于Golang的类型安全的Redis客户端
高级语言: Go
项目地址: git://github.com/go-redis/redis.git
创建时间: 2012-07-25T13:01:39Z
项目社区:https://github.com/go-redis/redis

开源协议:BSD 2-Clause "Simplified" License

关键词:
redis-cluster redis-client redis golang go

下载


Redis client for Go

build workflow
PkgGoDev
Documentation
codecov
Chat

go-redis is the official Redis client library for the Go programming language. It offers a straightforward interface for interacting with Redis servers.

Supported versions

In go-redis we are aiming to support the last three releases of Redis. Currently, this means we do support:

  • Redis 7.2 - using Redis Stack 7.2 for modules support
  • Redis 7.4 - using Redis Stack 7.4 for modules support
  • Redis 8.0 - using Redis CE 8.0 where modules are included

Although the go.mod states it requires at minimum go 1.18, our CI is configured to run the tests against all three
versions of Redis and latest two versions of Go (1.23,
1.24). We observe that some modules related test may not pass with
Redis Stack 7.2 and some commands are changed with Redis CE 8.0.
Please do refer to the documentation and the tests if you experience any issues. We do plan to update the go version
in the go.mod to go 1.24 in one of the next releases.

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:

  1. go mod init github.com/my/repo

Then install go-redis/v9:

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

Quickstart

  1. import (
  2. "context"
  3. "fmt"
  4. "github.com/redis/go-redis/v9"
  5. )
  6. var ctx = context.Background()
  7. func ExampleClient() {
  8. rdb := redis.NewClient(&redis.Options{
  9. Addr: "localhost:6379",
  10. Password: "", // no password set
  11. DB: 0, // use default DB
  12. })
  13. err := rdb.Set(ctx, "key", "value", 0).Err()
  14. if err != nil {
  15. panic(err)
  16. }
  17. val, err := rdb.Get(ctx, "key").Result()
  18. if err != nil {
  19. panic(err)
  20. }
  21. fmt.Println("key", val)
  22. val2, err := rdb.Get(ctx, "key2").Result()
  23. if err == redis.Nil {
  24. fmt.Println("key2 does not exist")
  25. } else if err != nil {
  26. panic(err)
  27. } else {
  28. fmt.Println("key2", val2)
  29. }
  30. // Output: key value
  31. // key2 does not exist
  32. }

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

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

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.

  1. import (
  2. "github.com/redis/go-redis/v9"
  3. )
  4. func ExampleClient() *redis.Client {
  5. url := "redis://user:password@localhost:6379/0?protocol=3"
  6. opts, err := redis.ParseURL(url)
  7. if err != nil {
  8. panic(err)
  9. }
  10. return redis.NewClient(opts)
  11. }

Instrument with OpenTelemetry

  1. import (
  2. "github.com/redis/go-redis/v9"
  3. "github.com/redis/go-redis/extra/redisotel/v9"
  4. "errors"
  5. )
  6. func main() {
  7. ...
  8. rdb := redis.NewClient(&redis.Options{...})
  9. if err := errors.Join(redisotel.InstrumentTracing(rdb), redisotel.InstrumentMetrics(rdb)); err != nil {
  10. log.Fatal(err)
  11. }

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 DisableIdentity configuration option exists.
Initially there was a typo and the option was named DisableIndentity instead of DisableIdentity. The misspelled option is marked as Deprecated and will be removed in V10 of this library.
Although both options will work at the moment, the correct option is DisableIdentity. The deprecated option will be removed in V10 of this library, so please use the correct option name to avoid any issues.

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

  1. rdb := redis.NewClient(&redis.Options{
  2. Addr: "localhost:6379",
  3. Password: "",
  4. DB: 0,
  5. DisableIdentity: true, // Disable set-info on connect
  6. })

Unstable RESP3 Structures for RediSearch Commands

When integrating Redis with application functionalities using RESP3, it’s important to note that some response structures aren’t final yet. This is especially true for more complex structures like search and query results. We recommend using RESP2 when using the search and query capabilities, but we plan to stabilize the RESP3-based API-s in the coming versions. You can find more guidance in the upcoming release notes.

To enable unstable RESP3, set the option in your client configuration:

  1. redis.NewClient(&redis.Options{
  2. UnstableResp3: true,
  3. })

Note: When UnstableResp3 mode is enabled, it’s necessary to use RawResult() and RawVal() to retrieve a raw data.
Since, raw response is the only option for unstable search commands Val() and Result() calls wouldn’t have any affect on them:

  1. res1, err := client.FTSearchWithArgs(ctx, "txt", "foo bar", &redis.FTSearchOptions{}).RawResult()
  2. val1 := client.FTSearchWithArgs(ctx, "txt", "foo bar", &redis.FTSearchOptions{}).RawVal()

Redis-Search Default Dialect

In the Redis-Search module, the default dialect is 2. If needed, you can explicitly specify a different dialect using the appropriate configuration in your queries.

Important: Be aware that the query dialect may impact the results returned. If needed, you can revert to a different dialect version by passing the desired dialect in the arguments of the command you want to execute.
For example:

  1. res2, err := rdb.FTSearchWithArgs(ctx,
  2. "idx:bicycle",
  3. "@pickup_zone:[CONTAINS $bike]",
  4. &redis.FTSearchOptions{
  5. Params: map[string]interface{}{
  6. "bike": "POINT(-0.1278 51.5074)",
  7. },
  8. DialectVersion: 3,
  9. },
  10. ).Result()

You can find further details in the query dialect documentation.

Contributing

We welcome contributions to the go-redis library! If you have a bug fix, feature request, or improvement, please open an issue or pull request on GitHub.
We appreciate your help in making go-redis better for everyone.
If you are interested in contributing to the go-redis library, please check out our contributing guidelines for more information on how to get started.

Look and feel

Some corner cases:

  1. // SET key value EX 10 NX
  2. set, err := rdb.SetNX(ctx, "key", "value", 10*time.Second).Result()
  3. // SET key value keepttl NX
  4. set, err := rdb.SetNX(ctx, "key", "value", redis.KeepTTL).Result()
  5. // SORT list LIMIT 0 2 ASC
  6. vals, err := rdb.Sort(ctx, "list", &redis.Sort{Offset: 0, Count: 2, Order: "ASC"}).Result()
  7. // ZRANGEBYSCORE zset -inf +inf WITHSCORES LIMIT 0 2
  8. vals, err := rdb.ZRangeByScoreWithScores(ctx, "zset", &redis.ZRangeBy{
  9. Min: "-inf",
  10. Max: "+inf",
  11. Offset: 0,
  12. Count: 2,
  13. }).Result()
  14. // ZINTERSTORE out 2 zset1 zset2 WEIGHTS 2 3 AGGREGATE SUM
  15. vals, err := rdb.ZInterStore(ctx, "out", &redis.ZStore{
  16. Keys: []string{"zset1", "zset2"},
  17. Weights: []int64{2, 3}
  18. }).Result()
  19. // EVAL "return {KEYS[1],ARGV[1]}" 1 "key" "hello"
  20. vals, err := rdb.Eval(ctx, "return {KEYS[1],ARGV[1]}", []string{"key"}, "hello").Result()
  21. // custom command
  22. 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:

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

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/:

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

Lastly, run:

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

  1. REDIS_PORT=9999 go test <your options>

See also

Contributors

The go-redis project was originally initiated 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.

Thanks to all the people who already contributed!