Giter VIP home page Giter VIP logo

go-redis's Introduction

Redis client for Go

build workflow PkgGoDev Documentation Chat

go-redis is brought to you by ⭐ 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!

go-redis's People

Contributors

alexanderyastrebov avatar allenwq avatar andriikushch avatar anmic avatar ash2k avatar chayim avatar dependabot[bot] avatar dim avatar elena-kolevska avatar etiennem avatar felipejfc avatar flisky avatar git-hulk avatar j178 avatar kavu avatar knadh avatar knutzuidema avatar monkey92t avatar mrchencode avatar nigelis avatar ofekshenawa avatar peczenyj avatar renovate-bot avatar rfyiamcool avatar smacker avatar soulpancake avatar szyhf avatar timvaillancourt avatar vmihailenco avatar wjdqhry avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

go-redis's Issues

Pipelining EVALSHA

When its requried to send multiple EVALSHA in a pipeline is it OK to do it like this:

pipeline := client.Pipeline()
script := redis.NewScript(`...`)
script.EvalSha(pipeline.Client)

?

Is There Any Way To Connect With a URL?

Our Go app runs on Heroku and we were going to use the REDISTOGO Heroku add-on. REDISTOGO publishes REDISTOGO_URL environment variable that our app is supposed to consume. It's in this format:

redis://username:[email protected]:port/

Flipping though the API docs for go-redis, it doesn't look like Conn Options supports a URL connect string or even a username. Is this the case? I'm new to Go and I just want to make sure I'm reading it right.

If this is the case, I may try to send a PR that'll take a URL connect string a chop it up and use that.

Are MULTI/EXEC transactions thread-safe?

I was looking at the code that handles MULTI/EXEC. This comment seems to say that issuing transactions with MULTI/EXEC is not thread-safe. I.e., if you have multiple connections issuing transactions in different threads, it could result in commands being received in the wrong order (e.g. redis server receiving MULTI twice before receiving EXEC). I just wanted to make sure. Is the comment still correct?

Setting timeout does not seem to have an effect

When setting timeout options, it doesn't seem to effect the actual dial timeout. For example:

    glog.Infoln("Setting timeout to ", time.Duration(60*5)*time.Second

client = redis.NewClient(&redis.Options{
    Addr:        "localhost:31600",
    Password:     "",
    DB:           0,
    DialTimeout:  time.Duration(60*5)*time.Second,
    ReadTimeout:  time.Duration(60*5)*time.Second,
    WriteTimeout: time.Duration(60*5)*time.Second,
})
    _, _ := client.Pong().Result()

Assuming no Redis server is running at all, this should take 5m to timeout if I'm interpreting the docs right. But when I execute:

% time go run main.go 

I get

I0810 15:17:09.897471 43124 main.go:22] Setting timeouts to:  5m0s
 dial tcp 172.31.2.11:31600: operation timed out
go runmain.go -logtostderr 0.33s user 0.08s system 0% cpu 1:15.75 total

So only 1m15s.

ZRevRangeWithScores arguments are String

Not really a problem, but different from ZRangeWithScores

func (c *Client) ZRangeWithScores(key string, start, stop int64) *ZSliceCmd

func (c *Client) ZRevRangeWithScores(key, start, stop string) *ZSliceCmd

Reset commands

Hi,

I am working a redis-cluster wrapper extension, but I am missing a crucial bit. Because of potential redirects to other servers, I need to be able to reset errors on commands. Could you please add the following:

diff --git a/command.go b/command.go
index d7c76cf..2a7bca7 100644
--- a/command.go
+++ b/command.go
@@ -35,6 +35,7 @@ type Cmder interface {

        Err() error
        String() string
+       Reset()
 }

 func setCmdsErr(cmds []Cmder, e error) {
@@ -78,6 +79,10 @@ func (cmd *baseCmd) Err() error {
        return nil
 }

+func (cmd *baseCmd) Reset() {
+       cmd.err = nil
+}
+
 func (cmd *baseCmd) args() []string {
        return cmd._args
 }

Thanks,
D

No MaxRetries field in FailoverOptions struct

HI,

I noticed that there is a MaxRetries field in the Options struct, but not in the FailoverOptions.
Is this deliberate ? And if so, could you explain why you choose to not implement auto-retry with
a failover client ?

Cluster pipeline panic

After plugging the new master into a real-world app, I get these:

2015/04/13 12:34:20 http: panic serving 127.0.0.1:47736: runtime error: index out of range
goroutine 7 [running]:
net/http.func·011()
        $GOROOT/src/net/http/server.go:1130 +0xbb
gopkg.in/redis%2ev2.(*ClusterClient).slotAddrs(0xc208096000, 0x13e8, 0x0, 0x0, 0x0)
        $GOPATH/src/gopkg.in/redis.v2/cluster.go:78 +0xee
gopkg.in/redis%2ev2.(*ClusterPipeline).Exec(0xc2086153e0, 0xc208746000, 0x2710, 0x3000, 0x0, 0x0)
        $GOPATH/src/gopkg.in/redis.v2/cluster_pipeline.go:56 +0x2b8

Will debug too.

nil dereference in singleConnPool

Using 2cfe5df , we do get the following panic (I replaced the workspace path by XXX):

[signal 0xb code=0x1 addr=0x50 pc=0x652f55]
goroutine 1657784 [running]:
gopkg.in/redis%2ev3.(*singleConnPool).remove(0xc209555500, 0x0, 0x0)
    XXX/src/gopkg.in/redis.v3/pool.go:396 +0x55
gopkg.in/redis%2ev3.(*singleConnPool).Remove(0xc209555500, 0xc20a3217a0, 0x0, 0x0)
    XXX/src/gopkg.in/redis.v3/pool.go:392 +0x168
gopkg.in/redis%2ev3.(*baseClient).putConn(0xc2087b7640, 0xc20a3217a0, 0x7ff04bdbc050, 0xc20bc2b400)
    XXX/src/gopkg.in/redis.v3/redis.go:32 +0x250
gopkg.in/redis%2ev3.(*baseClient).process(0xc2087b7640, 0x7ff04bda98e0, 0xc2098a6230)
    XXX/src/gopkg.in/redis.v3/redis.go:73 +0x2cc
gopkg.in/redis%2ev3.*baseClient.(gopkg.in/redis%2ev3.process)·fm(0x7ff04bda98e0, 0xc2098a6230)
    XXX/src/gopkg.in/redis.v3/redis.go:185 +0x3b
gopkg.in/redis%2ev3.(*commandable).Process(0xc2091ee808, 0x7ff04bda98e0, 0xc2098a6230)
    XXX/src/gopkg.in/redis.v3/commands.go:30 +0x3b
gopkg.in/redis%2ev3.(*commandable).Select(0xc2091ee808, 0x22a, 0xc209555500)
    XXX/src/gopkg.in/redis.v3/commands.go:84 +0x11d
gopkg.in/redis%2ev3.(*conn).init(0xc20a3217a0, 0xc208162180, 0x0, 0x0)
    XXX/src/gopkg.in/redis.v3/conn.go:59 +0x225
gopkg.in/redis%2ev3.func·001(0xc208131c60, 0x0, 0x0)
    XXX/src/gopkg.in/redis.v3/conn.go:36 +0x1fb
gopkg.in/redis%2ev3.(*connPool).new(0xc2086325c0, 0x0, 0x0, 0x0)
    XXX/src/gopkg.in/redis.v3/pool.go:205 +0x169

This was with a Redis instance that was melting down (latencies above 5 seconds), and options.ReadTimeout == options.WriteTimeout == 5 * time.Second.

We do use many databases on this server, so my guess is that the Select() in conn.init failed, and lead to the connection being closed. Because the singleConnPool in cn.init is created with a nil pool, remove() does a nil dereference.

Can't manage to have a working pub/sub

Hi guys,

so far I've been doing this:

import (
    _redis "gopkg.in/redis.v3"
    "strconv"
    "time"
)

type Redis struct {
    Connector   *_redis.Client
    PubSub      *_redis.PubSub
}

var redis *Redis = nil

func NewRedis() bool {
    if redis == nil {
        redis = new(Redis)
        redis.Connector = _redis.NewClient(&_redis.Options{
            Addr: config.RedisHostname + ":" + strconv.FormatInt(config.RedisPort, 10),
            Password: "",
            DB: 0,
        })
        Logger.Log(nil, "Connected to Redis")
        err := redis.Init()
        if err != nil {
            Logger.Fatal(nil, "Cannot setup Redis:", err.Error())
            return false
        }
        return true
    }
    return false
}

func (this *Redis) Init() error {
    pubsub, err := this.Connector.Subscribe("test")
    if err != nil {
        return err
    }
    defer pubsub.Close()
    this.PubSub = pubsub
    for {
        msgi, err := this.PubSub.ReceiveTimeout(100 * time.Millisecond)
        if err != nil {
            Logger.Error(nil, "PubSub error:", err.Error())
            err = this.PubSub.Ping("")
            if err != nil {
                Logger.Error(nil, "PubSub failure:", err.Error())
                break
            }
            continue
        }
        switch msg := msgi.(type) {
            case *_redis.Message:
                Logger.Log(nil, "Received", msg.Payload, "on channel", msg.Channel)
        }
    }
    return nil
}

My Connector is a redis.Client, it's working because I was able to publish messages as well.

When I run my program, I get the following error:
PubSub error: WSARecv tcp 127.0.0.1:64505: i/o timeout

Do you have any idea of what I'm doing wrong ?

Failing sentinel is leacking goroutines

I discovered this one through a configuration mistake. I found the number of goroutines was growing and checked the logs, where I found:

2014/11/05 06:25:11 redis-sentinel: GetMasterAddrByName "mymaster" failed: redis: nil
2014/11/05 06:25:11 redis-sentinel: GetMasterAddrByName "mymaster" failed: redis: nil
2014/11/05 06:25:12 redis-sentinel: GetMasterAddrByName "mymaster" failed: redis: nil
2014/11/05 06:25:12 redis-sentinel: GetMasterAddrByName "mymaster" failed: redis: nil
2014/11/05 06:25:12 redis-sentinel: GetMasterAddrByName "mymaster" failed: redis: nil

Killing the app with SIGQUIT unveiled many, many:

goroutine 603852 [sleep]:
time.Sleep(0x3b9aca00)
        /usr/lib/go/src/pkg/runtime/time.goc:39 +0x31
gopkg.in/redis%2ev2.(*rateLimiter).loop(0xc20f80cb30, 0x3b9aca00, 0x3c)
        /home/app/Godeps/_workspace/src/gopkg.in/redis.v2/rate_limit.go:30 +0x87
created by gopkg.in/redis%2ev2.newRateLimiter
        /home/app/Godeps/_workspace/src/gopkg.in/redis.v2/rate_limit.go:18 +0x67

goroutine 603925 [sleep]:
time.Sleep(0x3b9aca00)
        /usr/lib/go/src/pkg/runtime/time.goc:39 +0x31
gopkg.in/redis%2ev2.(*rateLimiter).loop(0xc20ee8bcd0, 0x3b9aca00, 0x3c)
        /home/app/Godeps/_workspace/src/gopkg.in/redis.v2/rate_limit.go:30 +0x87
created by gopkg.in/redis%2ev2.newRateLimiter
        /home/app/Godeps/_workspace/src/gopkg.in/redis.v2/rate_limit.go:18 +0x67

goroutine 603879 [sleep]:
time.Sleep(0x3b9aca00)
        /usr/lib/go/src/pkg/runtime/time.goc:39 +0x31
gopkg.in/redis%2ev2.(*rateLimiter).loop(0xc20caa14c0, 0x3b9aca00, 0x3c)
        /home/app/Godeps/_workspace/src/gopkg.in/redis.v2/rate_limit.go:30 +0x87
created by gopkg.in/redis%2ev2.newRateLimiter
        /home/app/Godeps/_workspace/src/gopkg.in/redis.v2/rate_limit.go:18 +0x67

Any clues?

Publish / Subscribe for ClusterClient

Is there currently a way to subscribe to a cluster? The Publish / Subscribe methods are not exposed to the ClusterClient.

The spec (http://redis.io/topics/cluster-spec) says...

"In a Redis Cluster clients can subscribe to every node, and can also publish to every other node. The cluster will make sure that published messages are forwarded as needed."

The workaround that I see at the moment is to call client.ClusterNodes() and parse for a random master, then create a standard client and subscribe. This is fine, but it would finer to be able to have this done in the background.

Thanks for this tremendous project.

parse.go readLine() sometimes got []byte{} ,err==nil

the reply is about 100 bulks
when parseReply(),
after parsed 27 bulks, readLine() got []byte{} and err == nil, and then switch line[0] cause panic

i read the bufio.ReadLine document, this should never happen -_-

and if i request 20 bulks, the reply parsed ok.

Don't know why.

now replaced with redigo.

broken pipe error

Hello!

I'm currently using your package in a project and am having the following error:
write tcp 127.0.0.1:6379: broken pipe .

My implementation is here:
https://github.com/johnwilson/bytengine/blob/master/kernel/modules/auth.go#L320

I create the connections here:
https://github.com/johnwilson/bytengine/blob/master/kernel/modules/sysinit.go#L110

A print of the Req returned contains EOF in the string

Any help/suggestion will be greatly appreciated.

Thanks for making your client available to us!

Cheers

Error run on go 1.0

# github.com/vmihailenco/bufio
/usr/lib64/go/src/pkg/github.com/vmihailenco/bufio/bufio.go:245: function ends without a return statement

Support for redis:// urls

Hi,

I'm wondering if there is a way to connect using a redis url in the following format:

redis://username:password@host:port/

Scan

Here is a simple example:

package main

import (
    "fmt"
    "gopkg.in/redis.v3"
)

func Connect() *redis.Client {
    client := redis.NewClient(&redis.Options{
        Addr:     "127.0.0.1:6379",
    })

    return client
}

func main() {
    client := Connect()

    // Generate objects
    cursor, _, _ := client.Scan(0, "tracking_insert_click_*", 0).Result()

    if cursor > 0 {
        _, keys, _ := client.Scan(0, "tracking_insert_click_*", cursor).Result()
        fmt.Println(keys)

    }

}

Is this really the right way of using scan?

I tried initially the code from : https://github.com/go-redis/redis/blob/master/commands_test.go#L552

But I had no results.

Please clarify.

Mass insertion

Hello there, let's say I have to populate redis with 1M rows using:

    hashID := "7f3b5e"
    var skey string
    var sval string
    var hval string

    for i := 0; i < 1000001; i++ {
        skey = fmt.Sprintf("xkey%d", i)
        sval = fmt.Sprintf("xval%d", i)
        hval = fmt.Sprintf("068%08d:1:0:1:1", i)
        client.Set(skey, sval).Result()
        client.HSet(hashID, skey, hval).Result()
    }

It works but it's way to slow but after the load the program only has 2MB on memory.

Now let's try using pipeline:

    hashID := "7f3b5e"
    var skey string
    var sval string
    var hval string

    for i := 0; i < 1000001; i++ {
        skey = fmt.Sprintf("xkey%d", i)
        sval = fmt.Sprintf("xval%d", i)
        hval = fmt.Sprintf("068%08d:1:0:1:1", i)        
        pipeline.Set(skey, sval)
        pipeline.HSet(hashID, sval, hval)
    }
    pipeline.Exec()

It loads fast but now the program has 942MB on memory and it keeps there for several minutes and then reduces slowly.

I'm doing it right? or there's a better way ?

thanks

Is there any plans to supported timeout?

We are working on an bad network now. Any packet can be lost very easy.
So, we need a timeout-kind mechanism to prevent it blocking forever(or very long time).
I know I can wrap the network request into a goroutine and use select to specified a timeout, but I think this way is too weird! The simplest way is call the Conn.SetDeadline() on baseClient.

If you guys would accept that way I suggested, I will pull my request as soon as possible. :)

EOF errors / automatic reconnnect?

We have EOF issues with v2 with idle connections. Our redis server is configured with timeout, when connections are idle for longer, we get an EOF error on the next request. We tried to lower/set the IdleTimeout option, but it causes a deadlock.

How to reproduce:

  1. Start redis-server with --timeout 5
  2. go run the code snippets below
package main

import (
    "fmt"
    redis "github.com/vmihailenco/redis/v2"
    "time"
)

func main() {
    red := redis.NewTCPClient(&redis.Options{Addr: "localhost:6379"})
    for {
        val := red.Ping()
        fmt.Println(val)
        time.Sleep(6 * time.Second)
    }
}
package main

import (
    "fmt"
    redis "github.com/vmihailenco/redis/v2"
    "time"
)

func main() {
    red := redis.NewTCPClient(&redis.Options{Addr: "localhost:6379", IdleTimeout: 3})
    for {
        val := red.Ping()
        fmt.Println(val)
        time.Sleep(6 * time.Second)
    }
}

Client.HGet().Err() behaving oddly

  • reflect.TypeOf(cmd.Err()) returns *errors.errorString
  • cmd.Err() != nil is true
  • fmt.Println(cmd.Err()) says (nil)

Maybe I'm just new to Go but this is clearly very odd. In case of no error, shouldn't cmd.Err() be <nil>?

Hash replies support

It would be nice for reply.Val() to return map[string]string for hash queries to Redis (HGetAll() etc.) instead of []string. Would require new reply type it seems.

Many "you open connections too fast" errors

We use the client in a high-frequency environment and the pools tend to grow quite quickly, especially on "boot". In these situation, we experience quite a few "you open connections too fast" errors, but I am not sure I understand the rationale behind the rate limiter. Could you please explain?

String overhead

Soo, this is something I wanted to discuss a long time ago, now that you have started working on #118, I think it's the right time. The client is currently using strings for arguments across the board. These strings are then converted to []byte and sent across the wire. Responses are received as byte streams and then converted (mostly) to strings again. This is quite inefficient if you are dealing with larger objects at higher frequency as it causes many allocations and therefore GC overhead. I was wondering if it would be sensible to implement most command methods using low-overhead []byte and then have MethodNameString/MethodNameValue accessors. Example:

func (c *commandable) Set(key, value []byte)
func (c *commandable) SetString(key, value string)
func (c *commandable) SetValue(key string, value interface{})

Alternatively:

func (c *commandable) SetBytes(key, value []byte)
func (c *commandable) Set(key, value string) // calls SetBytes internally
func (c *commandable) SetValue(key string, value interface{})  // calls SetBytes internally

I don't know how valuable this would be for everyone else, but it would make a huge difference for us.

Redis Cluster

Are you planning on implementing Redis Cluster anytime soon ? Are you waiting for it to be production ready ? Or are you simply not interested ?

add license please

under which license is this work distributed? is it safe to use it in greater projects?

Close rate-limiter when closing pool

Looks like your patch for #37 didn't work. When using the latest master, I am still getting this after a SIGQUIT:

goroutine 392 [sleep]:
time.Sleep(0x3b9aca00)
        /usr/lib/go/src/pkg/runtime/time.goc:39 +0x31
gopkg.in/redis%2ev2.(*rateLimiter).loop(0xc20804a130, 0x3b9aca00)
        /app/Godeps/_workspace/src/gopkg.in/redis.v2/rate_limit.go:28 +0x63
created by gopkg.in/redis%2ev2.newRateLimiter
        /app/Godeps/_workspace/src/gopkg.in/redis.v2/rate_limit.go:18 +0xd3

goroutine 280 [sleep]:
time.Sleep(0x3b9aca00)
        /usr/lib/go/src/pkg/runtime/time.goc:39 +0x31
gopkg.in/redis%2ev2.(*rateLimiter).loop(0xc208130258, 0x3b9aca00)
        /app/Godeps/_workspace/src/gopkg.in/redis.v2/rate_limit.go:28 +0x63
created by gopkg.in/redis%2ev2.newRateLimiter
        /app/Godeps/_workspace/src/gopkg.in/redis.v2/rate_limit.go:18 +0xd3

goroutine 294 [sleep]:
time.Sleep(0x3b9aca00)
        /usr/lib/go/src/pkg/runtime/time.goc:39 +0x31
gopkg.in/redis%2ev2.(*rateLimiter).loop(0xc2080e00f8, 0x3b9aca00)
        /app/Godeps/_workspace/src/gopkg.in/redis.v2/rate_limit.go:28 +0x63
created by gopkg.in/redis%2ev2.newRateLimiter
        /app/Godeps/_workspace/src/gopkg.in/redis.v2/rate_limit.go:18 +0xd3

Thousands of them unfortunately.

Unclear how to get values from pipeline.Exec()

Hi, I'm not sure how to get values from pipeline.Exec().

cmd.Val() results in type redis.Cmder has no field or method Val

It's very odd because reflect.TypeOf(cmd) does indeed return *redis.StringCmd, and both the docs and the code quite clearly indicate that the Val() method should be working.

Set without expiration

For this function:

func (c *Client) Set(key string, value interface{}, expiration time.Duration) *StatusCmd

Is there a way to set without having an expiration time as a really far time from now? Will nil work?

set command with XX options

Is there any command in the library that only set the key if it already exist?
I found set with xx options can fix this problem. But it is not in the library.

please look at http://redis.io/commands/set
I can use CustomCommand to workaround this right now.

problem with go get io.ErrNoProgress

Greetings,

I have problem doing go get with your package. any idea why I am receiving this? I have no problems doing go get to other packages..

thanks for the help!

-> % go get gopkg.in/redis.v2

gopkg.in/bufio.v1

gopkg.in/bufio.v1/bufio.go:110: undefined: io.ErrNoProgress
gopkg.in/bufio.v1/bufio.go:697: undefined: io.ErrNoProgress

Consider adding support for "DEBUG OBJECT"

http://redis.io/commands/debug-object states this command should not be added to clients but I have not found an alternative way to get key size estimates except for actually retrieving each value and determining its size.

This simple addition to commands.go does the trick:

func (c *Client) DebugObject(key string) *StringReq {
    req := NewStringReq("DEBUG", "OBJECT", key)
    c.Process(req)
    return req
}

"panic: runtime error: invalid memory address or nil pointer dereference" on large dataset when using Keys()

Hi,

My environment:

$ uname -a
Linux cm-x1c 3.5.0-32-generic #53-Ubuntu SMP Wed May 29 20:23:04 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

$ go version
go version devel +1c764773c6ce Tue Jun 04 08:33:00 2013 +0200 linux/amd64

I am using your debug branch as suggested in #7.

Here's the error when running it:

[...]
redisTweetIds: managetwitter:brookyln:ids:*
2013/06/20 09:11:17 write: KEYS managetwitter:brookyln:ids:*
2013/06/20 09:11:17 read line: "*0", buf: ""
redisTweetIds: managetwitter:model:ids:*
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x0 pc=0x43a831]

goroutine 1 [running]:
github.com/vmihailenco/redis.(*Client).Keys(0x0, 0xc213982860, 0x19, 0x1)
    /home/charl/Projects/go/src/github.com/vmihailenco/redis/commands.go:76 +0xb1
main.redisTweetIds(0x0, 0xc2100e31b0, 0x5, 0x5)
    /home/charl/Projects/go/src/89n.com/thoth-riak-data-expire/thoth-riak-data-expire.go:87 +0x1ce
main.main()
    /home/charl/Projects/go/src/89n.com/thoth-riak-data-expire/thoth-riak-data-expire.go:139 +0x1a2
exit status 2

Here's a gdb session of the issue listing the last two operations before things fall apart:

[...]
2013/06/20 08:59:41 write: HKEYS managetwitter:Franco Bianco:ids:2013052219
2013/06/20 08:59:41 read line: "*2", buf: "$18\r\n337293267727159296\r\n$18\r\n337285339016224768\r\n"
2013/06/20 08:59:41 read line: "$18", buf: "337293267727159296\r\n$18\r\n337285339016224768\r\n"
2013/06/20 08:59:41 read line: "$18", buf: "337285339016224768\r\n"
redisTweetIds: managetwitter:edenbaylee:ids:*

Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7ffff66fb700 (LWP 28492)]
0x000000000043af99 in github.com/vmihailenco/redis.(*Client).Keys (c=0x0, pattern="managetwitter:edenbaylee:ids:*", ~anon1=0x1)
    at /home/charl/Projects/go/src/github.com/vmihailenco/redis/commands.go:76
76      c.Process(req)
(gdb) 
(gdb) 
(gdb) bt
#0  0x000000000043af99 in github.com/vmihailenco/redis.(*Client).Keys (c=0x0, pattern="managetwitter:edenbaylee:ids:*", ~anon1=0x1)
    at /home/charl/Projects/go/src/github.com/vmihailenco/redis/commands.go:76
#1  0x0000000000401717 in main.redisTweetIds (rdb=0x0, term="edenbaylee", ~anon2= []string *<error reading variable: Cannot access memory at address 0xe>)
    at /home/charl/Projects/go/src/89n.com/thoth-riak-data-expire/thoth-riak-data-expire.go:87
#2  0x0000000000401fbd in main.main () at /home/charl/Projects/go/src/89n.com/thoth-riak-data-expire/thoth-riak-data-expire.go:139

The failure is not related to a specific key of time period.

ZRevRange and ZRange should have the same interface.

func (c *Client) ZRange(key string, start, stop int64) *StringSliceCmd
func (c *Client) ZRevRange(key, start, stop string) *StringSliceCmd

The redis doc says that:

Apart from the reversed ordering, ZREVRANGE is similar to ZRANGE.

Redis EOF after a period of time - probably due to timeout

Hello,

While running in production an app which uses go-redis library, we observed that the first request to Redis after a longer period of inactivity fails. It seems that the connection "dies" if unused with err = EOF.

What is the suggested mechanism to re-connect transparently and to prevent failure for the failing initial request? Can the library auto-reconnect in case of failed connection?

The code is super-simple. It does a MGET command for several keys. Redis connection is initialized using:

func InitRedis(host string, db int64) {
    client = redis.NewClient(&redis.Options{
        Network:"tcp4",
        Addr: host,
        DB: db,
    })
}

//request to get
  v, err := client.MGet("cp:"+date, "ob:" + date).Result()
    if(err!=nil || err == redis.Nil){
        log.Println("Error while getting Redis keys: ", err)
        panic(err)
    }

Thanks,
Robert

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.