Git Product home page Git Product logo

go-redis's Introduction

This README is just a fast quick start document. You can find more detailed documentation at redis.io.

What is Redis?

Redis is often referred to as a data structures server. What this means is that Redis provides access to mutable data structures via a set of commands, which are sent using a server-client model with TCP sockets and a simple protocol. So different processes can query and modify the same data structures in a shared way.

Data structures implemented into Redis have a few special properties:

  • Redis cares to store them on disk, even if they are always served and modified into the server memory. This means that Redis is fast, but that it is also non-volatile.
  • The implementation of data structures emphasizes memory efficiency, so data structures inside Redis will likely use less memory compared to the same data structure modelled using a high-level programming language.
  • Redis offers a number of features that are natural to find in a database, like replication, tunable levels of durability, clustering, and high availability.

Another good example is to think of Redis as a more complex version of memcached, where the operations are not just SETs and GETs, but operations that work with complex data types like Lists, Sets, ordered data structures, and so forth.

If you want to know more, this is a list of selected starting points:

Building Redis

Redis can be compiled and used on Linux, OSX, OpenBSD, NetBSD, FreeBSD. We support big endian and little endian architectures, and both 32 bit and 64 bit systems.

It may compile on Solaris derived systems (for instance SmartOS) but our support for this platform is best effort and Redis is not guaranteed to work as well as in Linux, OSX, and *BSD.

It is as simple as:

% make

To build with TLS support, you'll need OpenSSL development libraries (e.g. libssl-dev on Debian/Ubuntu) and run:

% make BUILD_TLS=yes

To build with systemd support, you'll need systemd development libraries (such as libsystemd-dev on Debian/Ubuntu or systemd-devel on CentOS) and run:

% make USE_SYSTEMD=yes

To append a suffix to Redis program names, use:

% make PROG_SUFFIX="-alt"

You can build a 32 bit Redis binary using:

% make 32bit

After building Redis, it is a good idea to test it using:

% make test

If TLS is built, running the tests with TLS enabled (you will need tcl-tls installed):

% ./utils/gen-test-certs.sh
% ./runtest --tls

Fixing build problems with dependencies or cached build options

Redis has some dependencies which are included in the deps directory. make does not automatically rebuild dependencies even if something in the source code of dependencies changes.

When you update the source code with git pull or when code inside the dependencies tree is modified in any other way, make sure to use the following command in order to really clean everything and rebuild from scratch:

% make distclean

This will clean: jemalloc, lua, hiredis, linenoise and other dependencies.

Also if you force certain build options like 32bit target, no C compiler optimizations (for debugging purposes), and other similar build time options, those options are cached indefinitely until you issue a make distclean command.

Fixing problems building 32 bit binaries

If after building Redis with a 32 bit target you need to rebuild it with a 64 bit target, or the other way around, you need to perform a make distclean in the root directory of the Redis distribution.

In case of build errors when trying to build a 32 bit binary of Redis, try the following steps:

  • Install the package libc6-dev-i386 (also try g++-multilib).
  • Try using the following command line instead of make 32bit: make CFLAGS="-m32 -march=native" LDFLAGS="-m32"

Allocator

Selecting a non-default memory allocator when building Redis is done by setting the MALLOC environment variable. Redis is compiled and linked against libc malloc by default, with the exception of jemalloc being the default on Linux systems. This default was picked because jemalloc has proven to have fewer fragmentation problems than libc malloc.

To force compiling against libc malloc, use:

% make MALLOC=libc

To compile against jemalloc on Mac OS X systems, use:

% make MALLOC=jemalloc

Monotonic clock

By default, Redis will build using the POSIX clock_gettime function as the monotonic clock source. On most modern systems, the internal processor clock can be used to improve performance. Cautions can be found here: http://oliveryang.net/2015/09/pitfalls-of-TSC-usage/

To build with support for the processor's internal instruction clock, use:

% make CFLAGS="-DUSE_PROCESSOR_CLOCK"

Verbose build

Redis will build with a user-friendly colorized output by default. If you want to see a more verbose output, use the following:

% make V=1

Running Redis

To run Redis with the default configuration, just type:

% cd src
% ./redis-server

If you want to provide your redis.conf, you have to run it using an additional parameter (the path of the configuration file):

% cd src
% ./redis-server /path/to/redis.conf

It is possible to alter the Redis configuration by passing parameters directly as options using the command line. Examples:

% ./redis-server --port 9999 --replicaof 127.0.0.1 6379
% ./redis-server /etc/redis/6379.conf --loglevel debug

All the options in redis.conf are also supported as options using the command line, with exactly the same name.

Running Redis with TLS:

Please consult the TLS.md file for more information on how to use Redis with TLS.

Playing with Redis

You can use redis-cli to play with Redis. Start a redis-server instance, then in another terminal try the following:

% cd src
% ./redis-cli
redis> ping
PONG
redis> set foo bar
OK
redis> get foo
"bar"
redis> incr mycounter
(integer) 1
redis> incr mycounter
(integer) 2
redis>

You can find the list of all the available commands at https://redis.io/commands.

Installing Redis

In order to install Redis binaries into /usr/local/bin, just use:

% make install

You can use make PREFIX=/some/other/directory install if you wish to use a different destination.

make install will just install binaries in your system, but will not configure init scripts and configuration files in the appropriate place. This is not needed if you just want to play a bit with Redis, but if you are installing it the proper way for a production system, we have a script that does this for Ubuntu and Debian systems:

% cd utils
% ./install_server.sh

Note: install_server.sh will not work on Mac OSX; it is built for Linux only.

The script will ask you a few questions and will setup everything you need to run Redis properly as a background daemon that will start again on system reboots.

You'll be able to stop and start Redis using the script named /etc/init.d/redis_<portnumber>, for instance /etc/init.d/redis_6379.

Code contributions

By contributing code to the Redis project in any form, including sending a pull request via GitHub, a code fragment or patch via private email or public discussion groups, you agree to release your code under the terms of the Redis Software Grant and Contributor License Agreement. Redis software contains contributions to the original Redis core project, which are owned by their contributors and licensed under the 3BSD license. Any copy of that license in this repository applies only to those contributions. Redis releases all Redis project versions from 7.4.x and thereafter under the RSALv2/SSPL dual-license as described in the LICENSE.txt file included in the Redis source distribution.

Please see the CONTRIBUTING.md file in this source distribution for more information. For security bugs and vulnerabilities, please see SECURITY.md.

Redis Trademarks

The purpose of a trademark is to identify the goods and services of a person or company without causing confusion. As the registered owner of its name and logo, Redis accepts certain limited uses of its trademarks but it has requirements that must be followed as described in its Trademark Guidelines available at: https://redis.com/legal/trademark-guidelines/.

Redis internals

If you are reading this README you are likely in front of a Github page or you just untarred the Redis distribution tar ball. In both the cases you are basically one step away from the source code, so here we explain the Redis source code layout, what is in each file as a general idea, the most important functions and structures inside the Redis server and so forth. We keep all the discussion at a high level without digging into the details since this document would be huge otherwise and our code base changes continuously, but a general idea should be a good starting point to understand more. Moreover most of the code is heavily commented and easy to follow.

Source code layout

The Redis root directory just contains this README, the Makefile which calls the real Makefile inside the src directory and an example configuration for Redis and Sentinel. You can find a few shell scripts that are used in order to execute the Redis, Redis Cluster and Redis Sentinel unit tests, which are implemented inside the tests directory.

Inside the root are the following important directories:

  • src: contains the Redis implementation, written in C.
  • tests: contains the unit tests, implemented in Tcl.
  • deps: contains libraries Redis uses. Everything needed to compile Redis is inside this directory; your system just needs to provide libc, a POSIX compatible interface and a C compiler. Notably deps contains a copy of jemalloc, which is the default allocator of Redis under Linux. Note that under deps there are also things which started with the Redis project, but for which the main repository is not redis/redis.

There are a few more directories but they are not very important for our goals here. We'll focus mostly on src, where the Redis implementation is contained, exploring what there is inside each file. The order in which files are exposed is the logical one to follow in order to disclose different layers of complexity incrementally.

Note: lately Redis was refactored quite a bit. Function names and file names have been changed, so you may find that this documentation reflects the unstable branch more closely. For instance, in Redis 3.0 the server.c and server.h files were named redis.c and redis.h. However the overall structure is the same. Keep in mind that all the new developments and pull requests should be performed against the unstable branch.

server.h

The simplest way to understand how a program works is to understand the data structures it uses. So we'll start from the main header file of Redis, which is server.h.

All the server configuration and in general all the shared state is defined in a global structure called server, of type struct redisServer. A few important fields in this structure are:

  • server.db is an array of Redis databases, where data is stored.
  • server.commands is the command table.
  • server.clients is a linked list of clients connected to the server.
  • server.master is a special client, the master, if the instance is a replica.

There are tons of other fields. Most fields are commented directly inside the structure definition.

Another important Redis data structure is the one defining a client. In the past it was called redisClient, now just client. The structure has many fields, here we'll just show the main ones:

struct client {
    int fd;
    sds querybuf;
    int argc;
    robj **argv;
    redisDb *db;
    int flags;
    list *reply;
    // ... many other fields ...
    char buf[PROTO_REPLY_CHUNK_BYTES];
}

The client structure defines a connected client:

  • The fd field is the client socket file descriptor.
  • argc and argv are populated with the command the client is executing, so that functions implementing a given Redis command can read the arguments.
  • querybuf accumulates the requests from the client, which are parsed by the Redis server according to the Redis protocol and executed by calling the implementations of the commands the client is executing.
  • reply and buf are dynamic and static buffers that accumulate the replies the server sends to the client. These buffers are incrementally written to the socket as soon as the file descriptor is writable.

As you can see in the client structure above, arguments in a command are described as robj structures. The following is the full robj structure, which defines a Redis object:

struct redisObject {
    unsigned type:4;
    unsigned encoding:4;
    unsigned lru:LRU_BITS; /* LRU time (relative to global lru_clock) or
                            * LFU data (least significant 8 bits frequency
                            * and most significant 16 bits access time). */
    int refcount;
    void *ptr;
};

Basically this structure can represent all the basic Redis data types like strings, lists, sets, sorted sets and so forth. The interesting thing is that it has a type field, so that it is possible to know what type a given object has, and a refcount, so that the same object can be referenced in multiple places without allocating it multiple times. Finally the ptr field points to the actual representation of the object, which might vary even for the same type, depending on the encoding used.

Redis objects are used extensively in the Redis internals, however in order to avoid the overhead of indirect accesses, recently in many places we just use plain dynamic strings not wrapped inside a Redis object.

server.c

This is the entry point of the Redis server, where the main() function is defined. The following are the most important steps in order to startup the Redis server.

  • initServerConfig() sets up the default values of the server structure.
  • initServer() allocates the data structures needed to operate, setup the listening socket, and so forth.
  • aeMain() starts the event loop which listens for new connections.

There are two special functions called periodically by the event loop:

  1. serverCron() is called periodically (according to server.hz frequency), and performs tasks that must be performed from time to time, like checking for timed out clients.
  2. beforeSleep() is called every time the event loop fired, Redis served a few requests, and is returning back into the event loop.

Inside server.c you can find code that handles other vital things of the Redis server:

  • call() is used in order to call a given command in the context of a given client.
  • activeExpireCycle() handles eviction of keys with a time to live set via the EXPIRE command.
  • performEvictions() is called when a new write command should be performed but Redis is out of memory according to the maxmemory directive.
  • The global variable redisCommandTable defines all the Redis commands, specifying the name of the command, the function implementing the command, the number of arguments required, and other properties of each command.

commands.c

This file is auto generated by utils/generate-command-code.py, the content is based on the JSON files in the src/commands folder. These are meant to be the single source of truth about the Redis commands, and all the metadata about them. These JSON files are not meant to be used by anyone directly, instead that metadata can be obtained via the COMMAND command.

networking.c

This file defines all the I/O functions with clients, masters and replicas (which in Redis are just special clients):

  • createClient() allocates and initializes a new client.
  • The addReply*() family of functions are used by command implementations in order to append data to the client structure, that will be transmitted to the client as a reply for a given command executed.
  • writeToClient() transmits the data pending in the output buffers to the client and is called by the writable event handler sendReplyToClient().
  • readQueryFromClient() is the readable event handler and accumulates data read from the client into the query buffer.
  • processInputBuffer() is the entry point in order to parse the client query buffer according to the Redis protocol. Once commands are ready to be processed, it calls processCommand() which is defined inside server.c in order to actually execute the command.
  • freeClient() deallocates, disconnects and removes a client.

aof.c and rdb.c

As you can guess from the names, these files implement the RDB and AOF persistence for Redis. Redis uses a persistence model based on the fork() system call in order to create a process with the same (shared) memory content of the main Redis process. This secondary process dumps the content of the memory on disk. This is used by rdb.c to create the snapshots on disk and by aof.c in order to perform the AOF rewrite when the append only file gets too big.

The implementation inside aof.c has additional functions in order to implement an API that allows commands to append new commands into the AOF file as clients execute them.

The call() function defined inside server.c is responsible for calling the functions that in turn will write the commands into the AOF.

db.c

Certain Redis commands operate on specific data types; others are general. Examples of generic commands are DEL and EXPIRE. They operate on keys and not on their values specifically. All those generic commands are defined inside db.c.

Moreover db.c implements an API in order to perform certain operations on the Redis dataset without directly accessing the internal data structures.

The most important functions inside db.c which are used in many command implementations are the following:

  • lookupKeyRead() and lookupKeyWrite() are used in order to get a pointer to the value associated to a given key, or NULL if the key does not exist.
  • dbAdd() and its higher level counterpart setKey() create a new key in a Redis database.
  • dbDelete() removes a key and its associated value.
  • emptyData() removes an entire single database or all the databases defined.

The rest of the file implements the generic commands exposed to the client.

object.c

The robj structure defining Redis objects was already described. Inside object.c there are all the functions that operate with Redis objects at a basic level, like functions to allocate new objects, handle the reference counting and so forth. Notable functions inside this file:

  • incrRefCount() and decrRefCount() are used in order to increment or decrement an object reference count. When it drops to 0 the object is finally freed.
  • createObject() allocates a new object. There are also specialized functions to allocate string objects having a specific content, like createStringObjectFromLongLong() and similar functions.

This file also implements the OBJECT command.

replication.c

This is one of the most complex files inside Redis, it is recommended to approach it only after getting a bit familiar with the rest of the code base. In this file there is the implementation of both the master and replica role of Redis.

One of the most important functions inside this file is replicationFeedSlaves() that writes commands to the clients representing replica instances connected to our master, so that the replicas can get the writes performed by the clients: this way their data set will remain synchronized with the one in the master.

This file also implements both the SYNC and PSYNC commands that are used in order to perform the first synchronization between masters and replicas, or to continue the replication after a disconnection.

Script

The script unit is composed of 3 units:

  • script.c - integration of scripts with Redis (commands execution, set replication/resp, ...)
  • script_lua.c - responsible to execute Lua code, uses script.c to interact with Redis from within the Lua code.
  • function_lua.c - contains the Lua engine implementation, uses script_lua.c to execute the Lua code.
  • functions.c - contains Redis Functions implementation (FUNCTION command), uses functions_lua.c if the function it wants to invoke needs the Lua engine.
  • eval.c - contains the eval implementation using script_lua.c to invoke the Lua code.

Other C files

  • t_hash.c, t_list.c, t_set.c, t_string.c, t_zset.c and t_stream.c contains the implementation of the Redis data types. They implement both an API to access a given data type, and the client command implementations for these data types.
  • ae.c implements the Redis event loop, it's a self contained library which is simple to read and understand.
  • sds.c is the Redis string library, check https://github.com/antirez/sds for more information.
  • anet.c is a library to use POSIX networking in a simpler way compared to the raw interface exposed by the kernel.
  • dict.c is an implementation of a non-blocking hash table which rehashes incrementally.
  • cluster.c implements the Redis Cluster. Probably a good read only after being very familiar with the rest of the Redis code base. If you want to read cluster.c make sure to read the Redis Cluster specification.

Anatomy of a Redis command

All the Redis commands are defined in the following way:

void foobarCommand(client *c) {
    printf("%s",c->argv[1]->ptr); /* Do something with the argument. */
    addReply(c,shared.ok); /* Reply something to the client. */
}

The command function is referenced by a JSON file, together with its metadata, see commands.c described above for details. The command flags are documented in the comment above the struct redisCommand in server.h. For other details, please refer to the COMMAND command. https://redis.io/commands/command/

After the command operates in some way, it returns a reply to the client, usually using addReply() or a similar function defined inside networking.c.

There are tons of command implementations inside the Redis source code that can serve as examples of actual commands implementations (e.g. pingCommand). Writing a few toy commands can be a good exercise to get familiar with the code base.

There are also many other files not described here, but it is useless to cover everything. We just want to help you with the first steps. Eventually you'll find your way inside the Redis code base :-)

Enjoy!

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

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.

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.

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?

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

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/

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

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?

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 ?

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.

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

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.

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
}

add license please

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

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 ?

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

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 ?

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.

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?

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)

?

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.

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

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

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

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?

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

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

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

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.

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.

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.

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>?

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.

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.

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.

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.