radix

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Apr 10, 2012 License: BSD-3-Clause Imports: 11 Imported by: 0

README

radix

radix is a package for Go that implements an asynchronous Redis client. radix was originally forked from the Tideland-rdc redis client (http://code.google.com/p/tideland-rdc/) developed by Frank Mueller.

Installation

go get github.com/fzzbt/radix

To run the tests:

cd $GOROOT/src/pkg/radix
go test -v -bench=".*"

Getting started

Creating a Client instance is done as follows:

	import "radix"

	...

	c := radix.NewClient(radix.Configuration{
		Database: 0, // (default: 0)
		// Timeout in seconds
		Timeout: 10, // (default: 10)

		// Custom TCP/IP address or Unix path. (default: Address: "127.0.0.1:6379")
		// Address: "127.0.0.1:6379", 
		// Path: "/tmp/radix.sock"

		//* Optional parameters
		// Password for authenticating (default: "")
		// Auth: "my_password", 
		// Size of the connection pool (default: 50)
		// PoolSize: 50, 
		// Don't try to retry on LOADING error? (default: false)
		// NoLoadingRetry: false, 
	})
	defer c.Close()

As Redis is mostly a single threaded database, increasing the PoolSize parameter does not usually make much difference unless the latency to your server is very high. The default is set to 50 connections which should be fine for around 99.9% of cases. However, note that each Subscription instance requires its own connection until it's closed.

Sometimes Redis may give a LOADING error when it is loading keys from the disk. The default behaviour of radix is to retry connecting until Redis is done with it, but you may wish to override this behaviour with the NoLoadingRetry parameter.

Simple blocking commands are executed using Client.Command and Client.AsyncCommand methods. Executing multiple commands at once (pipelining) can be done with Client.MultiCommand or Client.Transaction methods. All of these methods return a Reply instance which contains the reply.

Here's a simple example how to call single commands:

reply := c.Command("set", "mykey", "myvalue")
if reply.Error() != nil {
	fmt.Printf("set failed: %s\n", reply.Error())
	return
}

reply = c.Command("get", "mykey")
if reply.Type() != radix.ReplyString {
	fmt.Printf("get failed: %s\n", reply.Error())
	return
}

fmt.Printf("mykey: %s\n", rep.Str())

The Client.Command method and alike take the command name as their first parameter, followed by variadic length ...interface{} parameter. The interface{} parameters are converted into byte strings as follows:

  • s []byte -> s
  • s string -> []byte(s)
  • s int -> strconv.Itoa(s)
  • s int8 -> strconv.FormatInt(int64(s), 10)
  • s int16 -> strconv.FormatInt(int64(s), 10)
  • s int32 -> strconv.FormatInt(int64(s), 10)
  • s int64 -> strconv.FormatInt(s, 10)
  • s bool -> "1", if true, otherwise "0"

Furthermore, there is special handling for slices and maps, eg.

  • []int{1,2,3} is the same as giving parameters: "1", "2", "3"
  • map[string]int{"foo":1, "bar":2} is the same as giving parameters: "foo", 1, "bar", 2

For more examples on how to use multi-commands, transactions, subscriptions and more, take a look at the example program in example/example.go.

API reference

API reference is available in http://gopkgdoc.appspot.com/pkg/github.com/fzzbt/radix.

Alternatively, run godoc for API reference:

godoc -http=:8080

and point your browser to http://localhost:8080/pkg/github.com/fzzbt/radix.

HACKING

If you make contributions to the project, please follow the guidelines below:

  • Maximum line-width is 110 characters.
  • Run "gofmt -tabs=true -tabwidth=4" for any Go code before committing. You may do this for all code files by running "make format".
  • Any copyright notices, etc. should not be put in any files containing program code to avoid clutter. Place them in separate files instead.
  • Avoid commenting trivial or otherwise obvious code.
  • Avoid writing fancy ascii-artsy comments.
  • Write terse code without too much newlines or other non-essential whitespace.
  • Separate code sections with "//* My section"-styled comments.

New developers should add themselves to the lists in AUTHORS and/or CONTRIBUTORS files, when submitting their first commit. See the CONTRIBUTORS file for details.

Copyright 2012 The "radix" Authors. See file AUTHORS and CONTRIBUTORS.
Unless otherwise noted, the source files are distributed under the BSD 3-Clause License found in the LICENSE file.

Documentation

Overview

Package radix implements an asynchronous Redis client.

Client is a structure for accessing a Redis database. After establishing a connection with NewClient, commands can be executed with Client.Command. Client.Command returns a Reply with different methods for accessing the retrieved values. Client.MultiCommand can be used for sending multiple commands in a single request and Client.Transaction offers a simple way for executing atomic requests. Client.Subscription returns a Subscription that can be used for listening published messages.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

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

Client manages the access to a database.

func NewClient

func NewClient(conf Configuration) *Client

NewClient creates a new accessor.

func (*Client) AsyncCommand

func (c *Client) AsyncCommand(cmd string, args ...interface{}) Future

AsyncCommand calls a Redis command asynchronously.

func (*Client) AsyncMultiCommand

func (c *Client) AsyncMultiCommand(f func(*MultiCommand)) Future

AsyncMultiCommand calls an asynchronous multi-command.

func (*Client) AsyncTransaction

func (c *Client) AsyncTransaction(f func(*MultiCommand)) Future

AsyncTransaction performs a simple asynchronous transaction.

func (*Client) Close

func (c *Client) Close()

Close closes all connections of the client.

func (*Client) Command

func (c *Client) Command(cmd string, args ...interface{}) *Reply

Command calls a Redis command.

func (*Client) MultiCommand

func (c *Client) MultiCommand(f func(*MultiCommand)) *Reply

MultiCommand calls a multi-command.

func (*Client) Subscription

func (c *Client) Subscription(msgHdlr func(msg *Message)) (*Subscription, *Error)

Subscription subscribes to given channels and return a Subscription or an error. The msgHdlr function is called whenever a new message arrives.

func (*Client) Transaction

func (c *Client) Transaction(f func(*MultiCommand)) *Reply

Transaction performs a simple transaction. Simple transaction is a multi command that is wrapped in a MULTI-EXEC block. For complex transactions with WATCH, UNWATCH or DISCARD commands use MultiCommand.

type Configuration

type Configuration struct {
	Address        string
	Path           string
	Database       int
	Auth           string
	PoolSize       int
	Timeout        int
	NoLoadingRetry bool
}

Configuration of a database client.

type Error

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

func (*Error) Error

func (e *Error) Error() string

Error returns a string representation of the error.

func (*Error) Test

func (e *Error) Test(flags ...ErrorFlag) bool

Test returns true, if any of the given error flags is set in the error, otherwise false.

type ErrorFlag

type ErrorFlag uint8
const (
	ErrorRedis ErrorFlag = iota
	ErrorConnection
	ErrorLoading
	ErrorAuth
	ErrorParse
	ErrorInvalidReply
	ErrorTimeout
)

type Future

type Future chan *Reply

Future is a channel for fetching the reply of an asynchronous command.

func (Future) Reply

func (f Future) Reply() (r *Reply)

Reply returns the reply of the Future. It blocks until the reply is available.

type Message

type Message struct {
	Type          MessageType
	Channel       string
	Pattern       string
	Subscriptions int
	Payload       string
	Error         error
}

Message describes a pub/sub message

func (*Message) String

func (m *Message) String() string

String returns a string representation of the message.

type MessageType

type MessageType int
const (
	MessageSubscribe MessageType = iota
	MessageUnsubscribe
	MessagePSubscribe
	MessagePUnsubscribe
	MessageMessage
	MessagePMessage
	MessageError
)

type MultiCommand

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

MultiCommand holds data for a Redis multi command.

func (*MultiCommand) Command

func (mc *MultiCommand) Command(cmd string, args ...interface{})

Command queues a command for later execution.

func (*MultiCommand) Flush

func (mc *MultiCommand) Flush() *Reply

Flush sends queued commands to the Redis server for execution and returns the returned Reply. The Reply associated with the MultiCommand will be reseted.

type Reply

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

Reply holds a Redis reply.

func (*Reply) At

func (r *Reply) At(i int) *Reply

At returns a Reply of a multi reply by its index. It panics, if the reply type is not ReplyMulti or if the index is out of range.

func (*Reply) Bool

func (r *Reply) Bool() bool

Bool returns true, if the reply value equals to 1 or "1", otherwise false. It panics, if the reply type is not ReplyInteger or ReplyString.

func (*Reply) Bytes

func (r *Reply) Bytes() []byte

Bytes is a convenience method for []byte(Reply.String()).

func (*Reply) Elems

func (r *Reply) Elems() []*Reply

Elems returns the elements (sub-replies) of a multi reply. It panics, if the reply type is not ReplyMulti.

func (*Reply) Error

func (r *Reply) Error() *Error

Error returns the error value of the reply or nil, if the reply type is not ReplyError.

func (*Reply) ErrorString

func (r *Reply) ErrorString() string

ErrorString returns the error string of the error value of the reply or an empty string, if the reply type is not ReplyError.

func (*Reply) Int

func (r *Reply) Int() int

Int is a convenience method for int(Reply.Int64()).

func (*Reply) Int64

func (r *Reply) Int64() int64

Int64 returns the reply value as a int64. It panics, if the reply type is not ReplyInteger.

func (*Reply) Len

func (r *Reply) Len() int

Len returns the number of elements in a multi reply. Zero is returned when reply type is not ReplyMulti.

func (*Reply) Map

func (r *Reply) Map() (map[string]*Reply, error)

Map returns a multi-bulk reply as a map[string]*Reply or an error. The reply elements must be in a "key value key value..."-style order.

func (*Reply) Nil

func (r *Reply) Nil() bool

Nil returns true, if the reply is a nil reply, otherwise false.

func (*Reply) Str

func (r *Reply) Str() string

Str returns the reply value as a string or a nil, if the reply type is ReplyNil. It panics, if the reply type is not ReplyNil, ReplyStatus or ReplyString.

func (*Reply) String

func (r *Reply) String() string

String returns a string representation of the reply and its sub-replies. This method is mainly used for debugging. Use method Reply.Str for fetching a string reply.

func (*Reply) StringMap

func (r *Reply) StringMap() (map[string]string, error)

StringMap returns a multi-bulk reply as a map[string]string or an error. The reply elements must be in a "key value key value..."-style order.

func (*Reply) Strings

func (r *Reply) Strings() ([]string, error)

Strings returns a multi-bulk reply as a slice of strings or an error. The reply type must be ReplyMulti and its elements must be ReplyString.

func (*Reply) Type

func (r *Reply) Type() ReplyType

Type returns the type of the reply.

type ReplyType

type ReplyType uint8

ReplyType describes the type of reply.

Possbile values are:

ReplyStatus -- status reply ReplyError -- error reply ReplyInteger -- integer reply ReplyNil -- nil reply ReplyString -- string reply ReplyMulti -- multi-bulk or multi-command reply

const (
	ReplyStatus ReplyType = iota
	ReplyError
	ReplyInteger
	ReplyNil
	ReplyString
	ReplyMulti
)

type Subscription

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

Subscription is a structure for holding a Redis subscription for multiple channels.

func (*Subscription) Close

func (s *Subscription) Close()

Close closes the Subscription and returns its connection to the connection pool.

func (*Subscription) PSubscribe

func (s *Subscription) PSubscribe(patterns ...string) *Error

PSubscribe subscribes to given patterns or returns an error.

func (*Subscription) PUnsubscribe

func (s *Subscription) PUnsubscribe(patterns ...string) *Error

PUnsubscribe unsubscribes from given patterns or returns an error.

func (*Subscription) Subscribe

func (s *Subscription) Subscribe(channels ...string) *Error

Subscribe subscribes to given channels or returns an error.

func (*Subscription) Unsubscribe

func (s *Subscription) Unsubscribe(channels ...string) *Error

Unsubscribe unsubscribes from given channels or returns an error.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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