redis

package module
v1.6.4 Latest Latest
Warning

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

Go to latest
Published: Jul 27, 2019 License: MIT Imports: 22 Imported by: 0

README

redis-go CircleCI Go Report Card GoDoc

Go package providing tools for building redis clients, servers and middleware.

Motivation

While there's already good client support for Redis in Go, when it comes to building middleware (which require server components) the landscape of options shrinks dramatically. The existing client libraries also have limitations when it comes to supporting newer Go features (like context.Context) and each of them adopts a different design, making it harder to integrate with other components of a system.
On the other hand, the standard net/http package has proven to have a simple, and still extensible design, making it possible to leverage composition to build software that is easier to develop, maintain and evolve.
This is where the redis-go package comes into play, it follows the same design than the standard net/http package while offering both client and server-side abstractions to build Redis-compatible software.

Client

package main

import (
    "context"
    "fmt"
    "time"

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

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    // Use the default client which is configured to connect to the redis server
    // running at localhost:6379.
    if err := redis.Exec(ctx, "SET", "hello", "world"); err != nil {
        fmt.Println(err)
    }

    // Passing request or response arguments is done by consuming the stream of
    // values.
    var args = redis.Query(ctx, "GET", "hello")
    var value string

    if args.Next(&value) {
        fmt.Println(value)
    }

    if err := args.Close(); err != nil {
        fmt.Println(err)
    }
}

Server

package main

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

func main() {
    // Starts a new server speaking the redis protocol, the server automatically
    // handle asynchronusly pipelining the requests and responses.
    redis.ListenAndServe(":6380", redis.HandlerFunc(func(res redis.ResponseWriter, req *redis.Request) {
        // Put the response in streaming mode, will send 3 values.
        res.WriteStream(3)

        // The response writer automatically encodes Go values into their RESP
        // representation.
        res.Write(1)
        res.Write(2)
        res.Write(3)
    }))
}

Metrics

package main

import (
    "net/http"

    "github.com/prometheus/client_golang/prometheus"

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

func main() {
    // Starts a new http server async for prom.
    go http.ListenAndServe(":8080", http.HandlerFunc(redis.ServeMetrics))

    // Starts a new counter for local usage.
    counter := redis.NewCounterVec("handler", "custom handler counter", []string{"cmd"})

    // Starts a new server speaking the redis protocol, the server automatically
    // handle asynchronusly pipelining the requests and responses.

    redis.ListenAndServe(":6380", redis.HandlerFunc(func(res redis.ResponseWriter, req *redis.Request) {
        for _, cmd := range req.Cmds {
            counter.With(prometheus.Labels{
                "cmd": cmd.Cmd,
            }).Inc()
        }

        // Put the response in streaming mode, will send 3 values.
        res.WriteStream(3)

        // The response writer automatically encodes Go values into their RESP
        // representation.
        res.Write(1)
        res.Write(2)
        res.Write(3)
    }))
}

Documentation

Overview

Package redis provides Redis client and server implementations.

Exec and Query make Redis requests.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrServerClosed is returned by Server.Serve when the server is closed.
	ErrNil                           = errors.New("redis: nil")
	ErrNilArgs                       = errors.New("cannot parse values from a nil argument list")
	ErrServerClosed                  = errors.New("redis: Server closed")
	ErrNegativeStreamCount           = errors.New("invalid call to redis.ResponseWriter.WriteStream with a negative value")
	ErrWriteStreamCalledAfterWrite   = errors.New("invalid call to redis.ResponseWriter.WriteStream after redis.ResponseWriter.Write was called")
	ErrWriteStreamCalledTooManyTimes = errors.New("multiple calls to ResponseWriter.WriteStream")
	ErrWriteCalledTooManyTimes       = errors.New("too many calls to redis.ResponseWriter.Write")
	ErrWriteCalledNotEnoughTimes     = errors.New("not enough calls to redis.ResponseWriter.Write")
	ErrHijacked                      = errors.New("invalid use of a hijacked redis.ResponseWriter")
	ErrNotHijackable                 = errors.New("the response writer is not hijackable")
	ErrNotRetryable                  = errors.New("the request cannot retry")
	ErrNotPipeline                   = errors.New("redis: not pipeline")
)
View Source
var DefaultClient = &Client{}

DefaultClient is the default client and is used by Exec and Query.

View Source
var (
	// ErrDiscard is the error returned to indicate that transactions are
	// discarded.
	ErrDiscard = resp.NewError("EXECABORT Transaction discarded.")
)

Functions

func Exec

func Exec(ctx context.Context, cmd string, args ...interface{}) error

Exec is a wrapper around DefaultClient.Exec.

func Int

func Int(args Args) (i int, err error)

Int parses an integer value from the list of arguments and closes it, returning an error if no integer could not be read.

func Int64

func Int64(args Args) (i int64, err error)

Int64 parses a 64 bits integer value from the list of arguments and closes it, returning an error if no integer could not be read.

func ListenAndServe

func ListenAndServe(addr string, handler Handler) error

ListenAndServe listens on the network address addr and then calls Serve with handler to handle requests on incoming connections.

ListenAndServe always returns a non-nil error.

func NewCounterVec added in v1.3.0

func NewCounterVec(name, help string, labels []string) *prometheus.CounterVec

NewCounterVec returns a *prometheus.CounterVec for handler usage.

func NewGaugeVec added in v1.3.0

func NewGaugeVec(name, help string, labels []string) *prometheus.GaugeVec

NewGaugeVec returns a *prometheus.GaugeVec for handler usage.

func NewHistogramVec added in v1.3.0

func NewHistogramVec(name, help string, labels []string) *prometheus.HistogramVec

NewHistogramVec returns a *prometheus.HistogramVec for handler usage.

func ParseArgs

func ParseArgs(args Args, dsts ...interface{}) error

ParseArgs reads a list of arguments into a sequence of destination pointers and closes it, returning any error that occurred while parsing the values.

func Serve

func Serve(l net.Listener, handler Handler) error

Serve accepts incoming Redis connections on the listener l, creating a new service goroutine for each. The service goroutines read requests and then call handler to reply to them.

Serve always returns a non-nil error.

func ServeMetrics added in v1.3.0

func ServeMetrics(w http.ResponseWriter, r *http.Request)

ServeMetrics exports prometheus metrics of internal server.

func String

func String(args Args) (s string, err error)

String parses a string value from the list of arguments and closes it, returning an error if no string could not be read.

Types

type Args

type Args interface {
	// Close closes the argument list, returning any error that occurred while
	// reading the values.
	Close() error

	// Len returns the number of values remaining to be read from this argument
	// list.
	Len() int

	// Next reads the next value from the argument list into dst, which must be
	// a pointer.
	Next(dst interface{}) bool
}

Args represents a list of arguments in Redis requests and responses.

Args is an interface because there are multiple implementations that load values from memory, or from network connections. Using an interface allows the code consuming the list of arguments to be agnostic of the actual source from which the values are read.

func List

func List(args ...interface{}) Args

List creates an argument list from a sequence of values.

func MultiArgs

func MultiArgs(args ...Args) Args

MultiArgs returns an Args value that produces values sequentially from all of the given argument lists.

func Query

func Query(ctx context.Context, cmd string, args ...interface{}) Args

Query is a wrapper around DefaultClient.Query.

type Client

type Client struct {
	// Addr is the server address used by the client's Exec or Query methods
	// are called.
	Addr string

	// Transport specifies the mechanism by which individual requests are made.
	// If nil, DefaultTransport is used.
	Transport RoundTripper

	// Timeout specifies a time limit for requests made by this Client. The
	// timeout includes connection time, any redirects, and reading the response.
	// The timer remains running after Exec, Query, or Do return and will
	// interrupt reading of the Response.Args.
	//
	// A Timeout of zero means no timeout.
	Timeout time.Duration
}

A Client is a Redis client. Its zero value (DefaultClient) is a usable client that uses DefaultTransport and connects to a redis server on localhost:6379.

The Client's Transport typically has internal state (cached TCP connections), so Clients should be reused instead of created as needed. Clients are safe for concurrent use by multiple goroutines.

func (*Client) Do

func (c *Client) Do(req *Request) (*Response, error)

Do sends an Redis request and returns an Redis response.

An error is returned if the transport failed to contact the Redis server, or if a timeout occurs. Redis protocol errors are returned by the Response.Args' Close method.

If the error is nil, the Response will contain a non-nil Args which the user is expected to close. If the Body is not closed, the Client's underlying RoundTripper (typically Transport) may not be able to re-use a persistent TCP connection to the server for a subsequent request.

The request Args, if non-nil, will be closed by the underlying Transport, even on errors.

Generally Exec or Query will be used instead of Do.

func (*Client) Exec

func (c *Client) Exec(ctx context.Context, cmd string, args ...interface{}) error

Exec issues a request with cmd and args to the Redis server at the address set on the client.

An error is returned if the request couldn't be sent or if the command was refused by the Redis server.

The context passed as first argument allows the operation to be canceled asynchronously.

func (*Client) MultiExec added in v1.0.0

func (c *Client) MultiExec(ctx context.Context, cmds ...Command) error

MultiExec issues a transaction composed of the given list of commands.

An error is returned if the request couldn't be sent or if the command was refused by the Redis server.

The context passed as first argument allows the operation to be canceled asynchronously.

func (*Client) MultiQuery added in v1.0.0

func (c *Client) MultiQuery(ctx context.Context, cmds ...Command) TxArgs

MultiQuery issues a transaction composed of the given list of commands to the Redis server at the address set on the client, returning the response's TxArgs (which is never nil).

The method automatically wraps the list of commands with MULTI and EXEC, it is an error to put those in the command list.

Any error occurring while querying the Redis server will be returned by the TxArgs.Close method of the returned value.

The context passed as first argument allows the operation to be canceled asynchronously.

func (*Client) Query

func (c *Client) Query(ctx context.Context, cmd string, args ...interface{}) Args

Query issues a request with cmd and args to the Redis server at the address set on the client, returning the response's Args (which is never nil).

Any error occurring while querying the Redis server will be returned by the Args.Close method of the returned value.

The context passed as first argument allows the operation to be canceled asynchronously.

type Command added in v0.3.0

type Command struct {
	// Cmd is the Redis command that's being sent with this request.
	Cmd string

	// Args is the list of arguments for the request's command. This field
	// may be nil for client requests if there are no arguments to send with
	// the request.
	//
	// For server request, Args is never nil, even if there are no values in
	// the argument list.
	Args Args
	// contains filtered or unexported fields
}

A Command represent a Redis command used withing a Request.

func (*Command) ParseArgs added in v1.0.0

func (cmd *Command) ParseArgs(dsts ...interface{}) error

ParseArgs parses the list of arguments from the command into the destination pointers, returning an error if something went wrong.

type CommandReader added in v0.3.0

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

CommandReader is a type produced by the Conn.ReadCommands method to read a single command or a sequence of commands belonging to the same transaction.

func (*CommandReader) Close added in v0.3.0

func (r *CommandReader) Close() error

Close closes the command reader, it must be called when all commands have been read from the reader in order to release the parent connection's read lock.

func (*CommandReader) Read added in v0.3.0

func (r *CommandReader) Read(cmd *Command) bool

Read reads the next command from the command reader, filling cmd with the name and list of arguments. The command's arguments Close method must be called in order to release the reader's lock before any other methods of the reader are called.

The method returns true if a command could be read, or false if there were no more commands to read from the reader.

type Commander added in v1.2.1

type Commander interface {
	ServeCommand(tripper RoundTripper, hashing ServerRing, w ResponseWriter, r *Request)
}

A Commander responds to a Redis CMD.

Except for reading the argument list, handlers should not modify the provided Request.

type CommanderFunc added in v1.2.1

type CommanderFunc func(tripper RoundTripper, hashing ServerRing, w ResponseWriter, r *Request)

The CommanderFunc type is an adapter to allow the use of ordinary functions as redis commanders. If fn is a function with the appropriate signature.

func (CommanderFunc) ServeCommand added in v1.2.1

func (fn CommanderFunc) ServeCommand(tripper RoundTripper, hashing ServerRing, w ResponseWriter, r *Request)

type Conn added in v0.3.0

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

Conn is a low-level API to represent client connections to redis.

func Dial added in v0.3.0

func Dial(network string, address string) (*Conn, error)

Dial connects to the redis server at the given address, returning a new client redis connection.

func DialContext added in v0.3.0

func DialContext(ctx context.Context, network string, address string) (*Conn, error)

Dial connects to the redis server at the given address, returning a new client redis connection. Connecting may be asynchronously cancelled by the context passed as first argument.

func NewClientConn added in v0.3.0

func NewClientConn(conn net.Conn) *Conn

NewClientConn creates a new redis connection from an already open client connections.

func NewServerConn added in v0.3.0

func NewServerConn(conn net.Conn) *Conn

NewServerConn creates a new redis connection from an already open server connections.

func (*Conn) Close added in v0.3.0

func (c *Conn) Close() error

Close closes the kafka connection.

func (*Conn) Flush added in v0.3.0

func (c *Conn) Flush() error

Flush flushes the connection's internal write buffer.

func (*Conn) LocalAddr added in v0.3.0

func (c *Conn) LocalAddr() net.Addr

LocalAddr returns the local network address.

func (*Conn) Read added in v0.3.0

func (c *Conn) Read(b []byte) (int, error)

Read reads up to len(b) bytes from c, returning the number of bytes read, and an error if something went wrong while reading from the connection.

The function is exposed for the sole purpose of satisfying the net.Conn interface, it doesn't check that the data read are leaving the connection in a valid state in regard to the semantics of the redis protocol.

func (*Conn) ReadArgs added in v0.3.0

func (c *Conn) ReadArgs() Args

ReadArgs opens a stream to read arguments from the redis connection.

The method never returns a nil Args value, the program has to call the Args' Close method before calling any of the connection's read methods.

If an error occurs while reading the list of arguments it will be returned by the call to the Args' Close method.

func (*Conn) ReadCommands added in v0.3.0

func (c *Conn) ReadCommands(retry bool) *CommandReader

ReadCommands returns a new CommandReader which reads the next set of commands from c.

The new CommandReader holds the connection's read lock, which is released only when its Close method is called, so a program must make sure to call that method or the connection will be left in an unusable state.

func (*Conn) ReadTxArgs added in v0.3.0

func (c *Conn) ReadTxArgs(n int) TxArgs

ReadTxArgs opens a stream to read the arguments in response to opening a transaction of size n (not including the opening MULTI and closing EXEC or DISCARD commands).

If an error occurs while reading the transaction queuing responses it will be returned by the TxArgs' Close method, the ReadTxArgs method never returns a nil object, even if the connection was closed.

func (*Conn) RemoteAddr added in v0.3.0

func (c *Conn) RemoteAddr() net.Addr

RemoteAddr returns the remote network address.

func (*Conn) SetDeadline added in v0.3.0

func (c *Conn) SetDeadline(t time.Time) error

SetDeadline sets the read and write deadlines associated with the connection. It is equivalent to calling both SetReadDeadline and SetWriteDeadline.

A deadline is an absolute time after which I/O operations fail with a timeout instead of blocking. The deadline applies to all future and pending I/O, not just the immediately following call to Read or Write. After a deadline has been exceeded, the connection may be closed if it was found to be in an unrecoverable state.

A zero value for t means I/O operations will not time out.

func (*Conn) SetReadDeadline added in v0.3.0

func (c *Conn) SetReadDeadline(t time.Time) error

SetReadDeadline sets the deadline for future Read calls and any currently-blocked Read call. A zero value for t means Read will not time out.

func (*Conn) SetWriteDeadline added in v0.3.0

func (c *Conn) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the deadline for future Write calls and any currently-blocked Write call. Even if write times out, it may return n > 0, indicating that some of the data was successfully written. A zero value for t means Write will not time out.

func (*Conn) Write added in v0.3.0

func (c *Conn) Write(b []byte) (int, error)

Write writes b to c, returning the number of bytes written, and an error if something went wrong while writing to the connection.

The function is exposed for the sole purpose of satisfying the net.Conn interface, it doesn't check that the data written to the connection are meaningful messages in the redis protocol.

func (*Conn) WriteArgs added in v0.3.0

func (c *Conn) WriteArgs(args Args) error

WriteArgs writes a sequence of arguments to the redis connection, returning nil on success or an error describing what went wrong.

On error, the connection is closed because it's not possible to determine if it was left it a recoverable state.

func (*Conn) WriteCommands added in v0.3.0

func (c *Conn) WriteCommands(cmds ...Command) error

WriteCommands writes a set of commands to c.

This is a low-level API intended to be called to write a set of client commands to a redis server, no check is done on the validity of the commands.

Calling WriteCommands with no arguments has no effect and won't return an error even if the connection has already been closed.

The argument list of each command is always fully consumed and closed, even if the method returns an error.

It is invalid to call this method on server connections in the redis protocol however it is not enforced at the connection level, applications are expected to respect the protocol semantics.

type Flusher

type Flusher interface {
	// Flush sends any buffered data to the client.
	Flush() error
}

The Flusher interface is implemented by ResponseWriters that allow a Redis handler to flush buffered data to the client.

type Handler

type Handler interface {
	// ServeRedis is called by a Redis server to handle requests.
	ServeRedis(ResponseWriter, *Request)
}

A Handler responds to a Redis request.

ServeRedis should write reply headers and data to the ResponseWriter and then return. Returning signals that the request is finished; it is not valid to use the ResponseWriter or read from the Request.Args after or concurrently with the completion of the ServeRedis call.

Except for reading the argument list, handlers should not modify the provided Request.

type HandlerFunc

type HandlerFunc func(ResponseWriter, *Request)

The HandlerFunc type is an adapter to allow the use of ordinary functions as Redis handlers. If f is a function with the appropriate signature.

func (HandlerFunc) ServeRedis

func (fn HandlerFunc) ServeRedis(res ResponseWriter, req *Request)

ServeRedis implements the Handler interface, calling f.

type Hijacker

type Hijacker interface {
	// Hijack lets the caller take over the connection. After a call to Hijack
	// the Redis server library will not do anything else with the connection.
	//
	// It becomes the caller's responsibility to manage and close the
	// connection.
	//
	// The returned net.Conn may have read or write deadlines already set,
	// depending on the configuration of the Server. It is the caller's
	// responsibility to set or clear those deadlines as needed.
	//
	// The returned bufio.Reader may contain unprocessed buffered data from the
	// client.
	Hijack() (net.Conn, *bufio.ReadWriter, error)
}

The Hijacker interface is implemented by ResponseWriters that allow a Redis handler to take over the connection.

type Logger added in v1.1.0

type Logger interface {
	Print(v ...interface{})
}

type Request

type Request struct {
	// For client requests, Addr is set to the address of the server to which
	// the request is sent.
	//
	// For server requests (when received in a Handler's ServeRedis method),
	// the Addr field contains the remote address of the client that sent the
	// request.
	Addr string

	// Cmds is the list of commands submitted by the request.
	Cmds []Command

	// If not nil, this context is used to control asynchronous cancellation of
	// the request when it is passed to a RoundTripper.
	Context context.Context
}

A Request represents a Redis request received by a server or to be sent by a client.

The field semantics differ slightly between client and server usage. In addition to the notes on the fields below, see the documentation for Request.Write and RoundTripper.

func NewRequest

func NewRequest(addr string, cmd string, args Args) *Request

NewRequest returns a new Request, given an address, command, and list of arguments.

func (*Request) Close added in v1.0.0

func (req *Request) Close() error

Close closes all arguments of the request command list.

func (*Request) IsTransaction added in v1.0.0

func (req *Request) IsTransaction() bool

IsTransaction returns true if the request is configured to run as a transaction, false otherwise.

type Response

type Response struct {
	// Args is the arguments list of the response.
	//
	// When the response is obtained from Transport.RoundTrip or from Client.Do
	// the Args field is never nil.
	Args Args

	// TxArgs is the argument list of response to requests that were sent as
	// transactions.
	TxArgs TxArgs
	// contains filtered or unexported fields
}

Response represents the response from a Redis request.

func (*Response) Close added in v1.0.0

func (resp *Response) Close() error

Close closes all arguments of the response.

func (*Response) IsRespArray added in v1.5.0

func (resp *Response) IsRespArray() bool

func (*Response) IsRespError added in v1.4.0

func (resp *Response) IsRespError() bool

IsRespError returns true if redis response with an error message. You can get error by calling response.Close() or build a new request by calling response.Retry() for retrying.

func (*Response) Retry added in v1.4.0

func (resp *Response) Retry() (req *Request, err error)

retry returns a new *Request if the response is retryable and nil. Otherwise, it returns an error indicates the request CANNOT apply retry.

type ResponseWriter

type ResponseWriter interface {
	// WriteStream is called if the server handler is going to produce a list of
	// values by calling Write repeatedly n times.
	//
	// The method cannot be called more than once, or after Write was called.
	WriteStream(n int) error

	// Write is called by the server handler to send values back to the client.
	//
	// Write may not be called more than once, or more than n times, when n is
	// passed to a previous call to WriteStream.
	Write(v interface{}) error
}

A ResponseWriter interface is used by a Redis handler to construct an Redis response.

A ResponseWriter may not be used after the Handler.ServeRedis method has returned.

type ReverseProxy

type ReverseProxy struct {
	// Transport specifies the mechanism by which individual requests are made.
	// If nil, DefaultTransport is used.
	Transport RoundTripper

	// The registry exposing the set of redis servers that the proxy routes
	// requests to.
	Registry ServerRegistry

	// ErrorLog specifies an optional logger for errors accepting connections
	// and unexpected behavior from handlers. If nil, logging goes to os.Stderr
	// via the log package's standard logger.
	ErrorLog Logger
}

ReverseProxy is the implementation of a redis reverse proxy.

func (*ReverseProxy) ServeRedis

func (proxy *ReverseProxy) ServeRedis(w ResponseWriter, r *Request)

ServeRedis satisfies the Handler interface.

type RoundTripper

type RoundTripper interface {
	// RoundTrip executes a single Redis transaction, returning/ a Response for
	// the provided Request.
	//
	// RoundTrip should not attempt to interpret the response. In particular,
	// RoundTrip must return err == nil if it obtained a response, regardless of
	// whether the response carries a protocol error. A non-nil err should be
	// reserved for failure to obtain a response.
	//
	// RoundTrip should not modify the request, except for consuming and closing
	// the Request's Args.
	//
	// RoundTrip must always close the argument list, including on errors, but
	// depending on the implementation may do so in a separate goroutine even
	// after RoundTrip returns. This means that callers wanting to reuse the
	// argument list for subsequent requests must arrange to wait for the Close
	// call before doing so.
	//
	// The Request's Addr and Cmd fields must be initialized.
	RoundTrip(*Request) (*Response, error)
}

RoundTripper is an interface representing the ability to execute a single Redis transaction, obtaining the Response for a given Request.

A RoundTripper must be safe for concurrent use by multiple goroutines.

var (
	// DefaultTransport is the default implementation of Transport and is used by
	// DefaultClient. It establishes network connections as needed and caches them
	// for reuse by subsequent calls.
	DefaultTransport RoundTripper = &Transport{
		PingTimeout:  10 * time.Second,
		PingInterval: 15 * time.Second,
	}

	// DefaultDialer is the default dialer used by Transports when no DialContext
	// is set.
	DefaultDialer = &net.Dialer{
		Timeout:       10 * time.Second,
		KeepAlive:     30 * time.Second,
		FallbackDelay: 100 * time.Millisecond,
	}
)

type Server

type Server struct {
	// The address to listen on, ":6379" if empty.
	//
	// The address may be prefixed with "tcp://" or "unix://" to specify the
	// type of network to listen on.
	Addr string

	// Handler invoked to handle Redis requests, must not be nil.
	Handler Handler

	// features of command retry and pipeline
	EnableRetry    bool
	EnablePipeline bool

	// ReadTimeout is the maximum duration for reading the entire request,
	// including the reading the argument list.
	ReadTimeout time.Duration

	// WriteTimeout is the maximum duration before timing out writes of the
	// response. It is reset whenever a new request is read.
	WriteTimeout time.Duration

	// IdleTimeout is the maximum amount of time to wait for the next request.
	// If IdleTimeout is zero, the value of ReadTimeout is used. If both are
	// zero, there is no timeout.
	IdleTimeout time.Duration

	// ErrorLog specifies an optional logger for errors accepting connections
	// and unexpected behavior from handlers. If nil, logging goes to os.Stderr
	// via the log package's standard logger.
	ErrorLog Logger
	// contains filtered or unexported fields
}

A Server defines parameters for running a Redis server.

func (*Server) Close

func (s *Server) Close() error

Close immediately closes all active net.Listeners and any connections. For a graceful shutdown, use Shutdown.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() error

ListenAndServe listens on the network address s.Addr and then calls Serve to handle requests on incoming connections. If s.Addr is blank, ":6379" is used. ListenAndServe always returns a non-nil error.

func (*Server) Serve

func (s *Server) Serve(l net.Listener) error

Serve accepts incoming connections on the Listener l, creating a new service goroutine for each. The service goroutines read requests and then call s.Handler to reply to them.

Serve always returns a non-nil error. After Shutdown or Close, the returned error is ErrServerClosed.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle and then shut down. If the provided context expires before the shutdown is complete, then the context's error is returned.

func (*Server) WithMetrics added in v1.6.1

func (s *Server) WithMetrics(opts metrics.Options) *Server

type ServerBlacklist added in v1.0.0

type ServerBlacklist interface {
	// Blacklist temporarily blacklists the given server endpoint.
	BlacklistServer(ServerEndpoint)
}

ServerBlacklist is implemented by some ServerRegistry to support black listing some server addresses.

type ServerCommander added in v1.2.1

type ServerCommander interface {
	LookupCommanders() map[string]Commander
}

The ServerCommander interface is an abstraction used to extend redis command.

type ServerEndpoint

type ServerEndpoint struct {
	Name string
	Addr string
}

A ServerEndpoint represents a single backend redis server.

func (ServerEndpoint) LookupServers

func (endpoint ServerEndpoint) LookupServers(ctx context.Context) (ServerRing, error)

LookupServers satisfies the ServerRegistry interface.

type ServerHandler added in v1.2.1

type ServerHandler interface {
	LookupHandlers() map[string]Handler
}

The ServerHandler interface is an abstraction used to extend redis handler.

type ServerList

type ServerList []ServerEndpoint

A ServerList represents a list of backend redis servers.

func (ServerList) LookupServers

func (list ServerList) LookupServers(ctx context.Context) (ServerRing, error)

LookupServers satisfies the ServerRegistry interface.

type ServerRegistry

type ServerRegistry interface {
	// LookupServers returns a list of redis server endpoints.
	LookupServers(ctx context.Context) (ServerRing, error)
}

The ServerRegistry interface is an abstraction used to expose a (potentially changing) list of backend redis servers.

type ServerRing added in v1.1.0

type ServerRing interface {
	// LookupServer returns a redis server based on servers and key hashing.
	LookupServer(key string) ServerEndpoint
}

The ServerRing interface is an abstraction used to pick a backend redis server for key among servers.

func NewHashRing added in v1.1.0

func NewHashRing(endpoints ...ServerEndpoint) ServerRing

type ServerRingFunc added in v1.1.0

type ServerRingFunc func(key string) ServerEndpoint

A ServerRingFunc satisfies the ServerRing interface of custom hashing func.

func (ServerRingFunc) LookupServer added in v1.1.0

func (fn ServerRingFunc) LookupServer(key string) ServerEndpoint

LookupServer satisfies the ServerRing interface.

type SubConn

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

SubConn represents a redis connection that has been switched to PUB/SUB mode.

Instances of SubConn are safe for concurrent use by multiple goroutines.

func NewSubConn

func NewSubConn(conn net.Conn) *SubConn

NewSubConn creates a new SubConn from a pre-existing network connection.

func (*SubConn) Close

func (sub *SubConn) Close() error

Close closes the connection, writing commands or reading messages from the connection after Close was called will return errors.

func (*SubConn) LocalAddr

func (sub *SubConn) LocalAddr() net.Addr

LocalAddr returns the local network address.

func (*SubConn) ReadMessage

func (sub *SubConn) ReadMessage() (channel string, message []byte, err error)

ReadMessage reads the stream of PUB/SUB messages from the connection and returns the channel and payload of the first message it received.

The program is expected to call ReadMessage in a loop to consume messages from the PUB/SUB channels that the connection was subscribed to.

func (*SubConn) RemoteAddr

func (sub *SubConn) RemoteAddr() net.Addr

RemoteAddr returns the remote network address.

func (*SubConn) SetDeadline

func (sub *SubConn) SetDeadline(t time.Time) error

SetDeadline sets the read and write deadlines associated with the connection. It is equivalent to calling both SetReadDeadline and SetWriteDeadline.

A deadline is an absolute time after which I/O operations fail with a timeout (see type Error) instead of blocking. The deadline applies to all future and pending I/O, not just the immediately following call to ReadMessage or WriteCommand. After a deadline has been exceeded, the connection can be refreshed by setting a deadline in the future.

An idle timeout can be implemented by repeatedly extending the deadline after successful ReadFrom or WriteTo calls.

A zero value for t means I/O operations will not time out.

func (*SubConn) SetReadDeadline

func (sub *SubConn) SetReadDeadline(t time.Time) error

SetReadDeadline sets the deadline for future ReadFrom calls and any currently-blocked ReadFrom call. A zero value for t means ReadFrom will not time out.

func (*SubConn) SetWriteDeadline

func (sub *SubConn) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the deadline for future WriteTo calls and any currently-blocked WriteTo call. Even if write times out, it may return n > 0, indicating that some of the data was successfully written. A zero value for t means WriteTo will not time out.

func (*SubConn) WriteCommand

func (sub *SubConn) WriteCommand(command string, channels ...string) (err error)

WriteCommand writes a PUB/SUB command to the connection. The command must be one of "SUBSCRIBE", "UNSUBSCRIBE", "PSUBSCRIBE", or "PUNSUBSCRIBE".

type Transport

type Transport struct {
	// DialContext specifies the dial function for creating network connections.
	// If DialContext is nil, then the transport dials using package net.
	DialContext func(context.Context, string, string) (net.Conn, error)

	// MaxIdleConns controls the maximum number of idle (keep-alive) connections
	// across all hosts. Zero means no limit.
	MaxIdleConns int

	// MaxIdleConnsPerHost, if non-zero, controls the maximum idle
	// (keep-alive) connections to keep per-host. Zero means no limit.
	MaxIdleConnsPerHost int

	// PingInterval is the amount of time between pings that the transport sends
	// to the hosts it connects to.
	PingInterval time.Duration

	// PingTimeout is the amount of time that the transport waits for responses
	// to ping requests before discarding connections.
	PingTimeout time.Duration
	// contains filtered or unexported fields
}

Transport is an implementation of RoundTripper.

By default, Transport caches connections for future re-use. This may leave many open connections when accessing many hosts. This behavior can be managed using Transport's CloseIdleConnections method and ConnsPerHost field.

Transports should be reused instead of created as needed. Transports are safe for concurrent use by multiple goroutines.

A Transport is a low-level primitive for making Redis requests. For high-level functionality, see Client.

func (*Transport) CloseIdleConnections

func (t *Transport) CloseIdleConnections()

CloseIdleConnections closes any connections which were previously connected from previous requests but are now sitting idle. It does not interrupt any connections currently in use.

func (*Transport) PSubscribe

func (t *Transport) PSubscribe(ctx context.Context, network string, address string, patterns ...string) (*SubConn, error)

PSubscribe uses the transport's configuration to open a connection to a redis server that subscribes to the given patterns.

func (*Transport) RoundTrip

func (t *Transport) RoundTrip(req *Request) (*Response, error)

RoundTrip implements the RoundTripper interface.

For higher-level Redis client support, see Exec, Query, and the Client type.

func (*Transport) Subscribe

func (t *Transport) Subscribe(ctx context.Context, network string, address string, channels ...string) (*SubConn, error)

Subscribe uses the transport's configuration to open a connection to a redis server that subscribes to the given channels.

type TxArgs added in v0.3.0

type TxArgs interface {
	Close() error

	// Len returns the number of argument lists remaining to consume.
	Len() int

	// Next returns the next argument list of the transaction, or nil if they have
	// all been consumed.
	//
	// When the returned value is not nil the program must call its Close method
	// before calling any other function of the TxArgs value.
	Next() Args
}

TxArgs is an interface implemented by types that produce the sequence of argument list in response to a transaction.

Directories

Path Synopsis
cmd
red
examples

Jump to

Keyboard shortcuts

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