Documentation ¶
Overview ¶
Package ssdb implements a ssdb client.
Example (Instrumentation) ¶
sdb := ssdb.NewClient(&ssdb.Options{ Addr: ":8888", }) sdb.AddHook(ssdbHook{}) sdb.Ping(ctx)
Output: starting processing: <ping: > finished processing: <ping: PONG>
Index ¶
- Constants
- Variables
- func SetLogger(logger internal.Logging)
- func Version() string
- type Client
- func (hs *Client) AddHook(hook Hook)
- func (c Client) Close() error
- func (c *Client) Conn() *Conn
- func (c Client) DBInfo(ctx context.Context) *Cmd
- func (c Client) DBSize(ctx context.Context) *Cmd
- func (c Client) Del(ctx context.Context, key string) *Cmd
- func (c *Client) Do(ctx context.Context, args ...interface{}) *Cmd
- func (c Client) Exists(ctx context.Context, key string) *Cmd
- func (c Client) Expire(ctx context.Context, key string, ttl int64) *Cmd
- func (c Client) Get(ctx context.Context, key string) *Cmd
- func (c Client) GetSet(ctx context.Context, key string, val interface{}) *Cmd
- func (c Client) HSet(ctx context.Context, key string, val ...interface{}) *Cmd
- func (c Client) Incr(ctx context.Context, key string, num int64) *Cmd
- func (c *Client) Options() *Options
- func (c Client) Ping(ctx context.Context) *Cmd
- func (c *Client) Pipeline() Pipeliner
- func (c *Client) Pipelined(ctx context.Context, fn func(Pipeliner) error) ([]Cmder, error)
- func (c Client) Pool() pool.Pooler
- func (c *Client) PoolStats() *PoolStats
- func (c *Client) Process(ctx context.Context, cmd Cmder) error
- func (c Client) Scan(ctx context.Context, keyStart, keyEnd string, limit int64) *Cmd
- func (c Client) Set(ctx context.Context, key string, val interface{}, ttl ...int64) *Cmd
- func (c Client) SetNX(ctx context.Context, key string, val interface{}) *Cmd
- func (c Client) String() string
- func (c Client) TTL(ctx context.Context, key string) *Cmd
- func (c *Client) TxPipeline() Pipeliner
- func (c *Client) TxPipelined(ctx context.Context, fn func(Pipeliner) error) ([]Cmder, error)
- func (c *Client) WithTimeout(timeout time.Duration) *Client
- type Cmd
- func NewBoolResult(val bool, err error) *Cmd
- func NewBoolSliceResult(val []bool, err error) *Cmd
- func NewCmd(ctx context.Context, args ...interface{}) *Cmd
- func NewCmdResult(val interface{}, err error) *Cmd
- func NewDurationResult(val time.Duration, err error) *Cmd
- func NewFloatResult(val float64, err error) *Cmd
- func NewIntResult(val int64, err error) *Cmd
- func NewMapStringIntCmdResult(val map[string]int64, err error) *Cmd
- func NewMapStringStringResult(val map[string]string, err error) *Cmd
- func NewSliceResult(val []interface{}, err error) *Cmd
- func NewStatusResult(val string, err error) *Cmd
- func NewStringResult(val string, err error) *Cmd
- func NewStringSliceResult(val []string, err error) *Cmd
- func NewTimeCmdResult(val time.Time, err error) *Cmd
- func (cmd *Cmd) Args() []interface{}
- func (cmd *Cmd) Bool() (bool, error)
- func (cmd *Cmd) BoolSlice() ([]bool, error)
- func (cmd *Cmd) Err() error
- func (cmd *Cmd) Float32() (float32, error)
- func (cmd *Cmd) Float32Slice() ([]float32, error)
- func (cmd *Cmd) Float64() (float64, error)
- func (cmd *Cmd) Float64Slice() ([]float64, error)
- func (cmd *Cmd) FullName() string
- func (cmd *Cmd) Int() (int, error)
- func (cmd *Cmd) Int64() (int64, error)
- func (cmd *Cmd) Int64Slice() ([]int64, error)
- func (cmd *Cmd) Name() string
- func (cmd *Cmd) Result() (interface{}, error)
- func (cmd *Cmd) SetErr(e error)
- func (cmd *Cmd) SetFirstKeyPos(keyPos int8)
- func (cmd *Cmd) SetVal(val interface{})
- func (cmd *Cmd) Slice() ([]interface{}, error)
- func (cmd *Cmd) String() string
- func (cmd *Cmd) StringSlice() ([]string, error)
- func (cmd *Cmd) Text() (string, error)
- func (cmd *Cmd) Uint64() (uint64, error)
- func (cmd *Cmd) Uint64Slice() ([]uint64, error)
- func (cmd *Cmd) Val() interface{}
- type Cmdable
- type Cmder
- type CommandInfo
- type CommandsInfoCmd
- func (cmd *CommandsInfoCmd) Args() []interface{}
- func (cmd *CommandsInfoCmd) Err() error
- func (cmd *CommandsInfoCmd) FullName() string
- func (cmd *CommandsInfoCmd) Name() string
- func (cmd *CommandsInfoCmd) Result() (map[string]*CommandInfo, error)
- func (cmd *CommandsInfoCmd) SetErr(e error)
- func (cmd *CommandsInfoCmd) SetFirstKeyPos(keyPos int8)
- func (cmd *CommandsInfoCmd) SetVal(val map[string]*CommandInfo)
- func (cmd *CommandsInfoCmd) String() string
- func (cmd *CommandsInfoCmd) Val() map[string]*CommandInfo
- type Conn
- type Error
- type Hook
- type Limiter
- type Options
- type Pipeline
- func (c Pipeline) Auth(ctx context.Context, password string) *Cmd
- func (c Pipeline) AuthACL(ctx context.Context, username, password string) *Cmd
- func (c Pipeline) ClientSetName(ctx context.Context, name string) *Cmd
- func (c Pipeline) DBInfo(ctx context.Context) *Cmd
- func (c Pipeline) DBSize(ctx context.Context) *Cmd
- func (c Pipeline) Del(ctx context.Context, key string) *Cmd
- func (c *Pipeline) Discard()
- func (c *Pipeline) Do(ctx context.Context, args ...interface{}) *Cmd
- func (c *Pipeline) Exec(ctx context.Context) ([]Cmder, error)
- func (c Pipeline) Exists(ctx context.Context, key string) *Cmd
- func (c Pipeline) Expire(ctx context.Context, key string, ttl int64) *Cmd
- func (c Pipeline) Get(ctx context.Context, key string) *Cmd
- func (c Pipeline) GetSet(ctx context.Context, key string, val interface{}) *Cmd
- func (c Pipeline) HSet(ctx context.Context, key string, val ...interface{}) *Cmd
- func (c Pipeline) Incr(ctx context.Context, key string, num int64) *Cmd
- func (c *Pipeline) Len() int
- func (c Pipeline) Ping(ctx context.Context) *Cmd
- func (c *Pipeline) Pipeline() Pipeliner
- func (c *Pipeline) Pipelined(ctx context.Context, fn func(Pipeliner) error) ([]Cmder, error)
- func (c *Pipeline) Process(ctx context.Context, cmd Cmder) error
- func (c Pipeline) Scan(ctx context.Context, keyStart, keyEnd string, limit int64) *Cmd
- func (c Pipeline) Set(ctx context.Context, key string, val interface{}, ttl ...int64) *Cmd
- func (c Pipeline) SetNX(ctx context.Context, key string, val interface{}) *Cmd
- func (c Pipeline) TTL(ctx context.Context, key string) *Cmd
- func (c *Pipeline) TxPipeline() Pipeliner
- func (c *Pipeline) TxPipelined(ctx context.Context, fn func(Pipeliner) error) ([]Cmder, error)
- type Pipeliner
- type PoolStats
- type ScanIterator
- type SlowLog
- type SlowLogCmd
- func (cmd *SlowLogCmd) Args() []interface{}
- func (cmd *SlowLogCmd) Err() error
- func (cmd *SlowLogCmd) FullName() string
- func (cmd *SlowLogCmd) Name() string
- func (cmd *SlowLogCmd) Result() ([]SlowLog, error)
- func (cmd *SlowLogCmd) SetErr(e error)
- func (cmd *SlowLogCmd) SetFirstKeyPos(keyPos int8)
- func (cmd *SlowLogCmd) SetVal(val []SlowLog)
- func (cmd *SlowLogCmd) String() string
- func (cmd *SlowLogCmd) Val() []SlowLog
- type StatefulCmdable
Examples ¶
Constants ¶
const KeepTTL = -1
KeepTTL is a ssdb KEEPTTL option to keep existing TTL, it requires your ssdb-server version >= 6.0, otherwise you will receive an error: (error) ERR syntax error. For example:
sdb.Set(ctx, key, value, ssdb.KeepTTL)
const Nil = proto.Nil
Nil reply returned by Ssdb when key does not exist.
Variables ¶
var ErrClosed = pool.ErrClosed
ErrClosed performs any operation on the closed client will return this error.
Functions ¶
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a Ssdb client representing a pool of zero or more underlying connections. It's safe for concurrent use by multiple goroutines.
Client creates and frees connections automatically; it also maintains a free pool of idle connections. You can control the pool size with Config.PoolSize option.
Example ¶
package main import ( "context" "fmt" "github.com/ssdb-go/ssdb" ) var ( ctx = context.Background() sdb *ssdb.Client ) func main() { err := sdb.Set(ctx, "key", "value", 0).Err() if err != nil { panic(err) } val, err := sdb.Get(ctx, "key").Result() if err != nil { panic(err) } fmt.Println("key", val) val2, err := sdb.Get(ctx, "missing_key").Result() if err == ssdb.Nil { fmt.Println("missing_key does not exist") } else if err != nil { panic(err) } else { fmt.Println("missing_key", val2) } }
Output: key value missing_key does not exist
func NewClient ¶
NewClient returns a client to the Ssdb Server specified by Options.
Example ¶
package main import ( "context" "fmt" "github.com/ssdb-go/ssdb" ) var ctx = context.Background() func main() { sdb := ssdb.NewClient(&ssdb.Options{ Addr: "localhost:8888", // use default Addr Password: "", // no password set DB: 0, // use default DB }) pong, err := sdb.Ping(ctx).Result() fmt.Println(pong, err) }
Output: PONG <nil>
func (Client) Close ¶
func (c Client) Close() error
Close closes the client, releasing any open resources.
It is rare to Close a Client, as the Client is meant to be long-lived and shared between many goroutines.
func (Client) DBSize ¶
------------------------------------------------------------------------------
func (Client) Set ¶
Example ¶
package main import ( "context" "github.com/ssdb-go/ssdb" ) var ( ctx = context.Background() sdb *ssdb.Client ) func main() { // Last argument is expiration. Zero means the key has no // expiration time. err := sdb.Set(ctx, "key", "value", 0).Err() if err != nil { panic(err) } // key2 will expire in an hour. err = sdb.Set(ctx, "key2", "value", 0).Err() if err != nil { panic(err) } }
Output:
func (*Client) TxPipeline ¶
TxPipeline acts like Pipeline, but wraps queued commands with MULTI/EXEC.
func (*Client) TxPipelined ¶
type Cmd ¶
type Cmd struct {
// contains filtered or unexported fields
}
func NewBoolResult ¶
NewBoolResult returns a Cmd initialised with val and err for testing.
func NewBoolSliceResult ¶
NewBoolSliceResult returns a Cmd initialised with val and err for testing.
func NewCmdResult ¶
NewCmdResult returns a Cmd initialised with val and err for testing.
func NewDurationResult ¶
NewDurationResult returns a Cmd initialised with val and err for testing.
func NewFloatResult ¶
NewFloatResult returns a Cmd initialised with val and err for testing.
func NewIntResult ¶
NewIntResult returns an Cmd initialised with val and err for testing.
func NewMapStringIntCmdResult ¶
NewMapStringIntCmdResult returns a Cmd initialised with val and err for testing.
func NewMapStringStringResult ¶
NewStringStringMapResult returns a StringStringMapCmd initialised with val and err for testing.
func NewSliceResult ¶
NewSliceResult returns a Cmd initialised with val and err for testing.
func NewStatusResult ¶
NewStatusResult returns a Cmd initialised with val and err for testing.
func NewStringResult ¶
NewStringResult returns a Cmd initialised with val and err for testing.
func NewStringSliceResult ¶
NewStringSliceResult returns a Cmd initialised with val and err for testing.
func NewTimeCmdResult ¶
NewTimeCmdResult returns a Cmd initialised with val and err for testing.
func (*Cmd) Float32Slice ¶
func (*Cmd) Float64Slice ¶
func (*Cmd) Int64Slice ¶
func (*Cmd) SetFirstKeyPos ¶
func (cmd *Cmd) SetFirstKeyPos(keyPos int8)
func (*Cmd) StringSlice ¶
func (*Cmd) Uint64Slice ¶
type Cmdable ¶
type Cmdable interface { Pipeline() Pipeliner Pipelined(ctx context.Context, fn func(Pipeliner) error) ([]Cmder, error) TxPipelined(ctx context.Context, fn func(Pipeliner) error) ([]Cmder, error) TxPipeline() Pipeliner // db server DBSize(ctx context.Context) *Cmd DBInfo(ctx context.Context) *Cmd Ping(ctx context.Context) *Cmd // key-value Set(ctx context.Context, key string, val interface{}, ttl ...int64) *Cmd SetNX(ctx context.Context, key string, val interface{}) *Cmd Get(ctx context.Context, key string) *Cmd GetSet(ctx context.Context, key string, val interface{}) *Cmd Del(ctx context.Context, key string) *Cmd HSet(ctx context.Context, key string, val ...interface{}) *Cmd Expire(ctx context.Context, key string, ttl int64) *Cmd Exists(ctx context.Context, key string) *Cmd TTL(ctx context.Context, key string) *Cmd Incr(ctx context.Context, key string, num int64) *Cmd }
type CommandInfo ¶
type CommandsInfoCmd ¶
type CommandsInfoCmd struct {
// contains filtered or unexported fields
}
func NewCommandsInfoCmd ¶
func NewCommandsInfoCmd(ctx context.Context, args ...interface{}) *CommandsInfoCmd
func (*CommandsInfoCmd) Result ¶
func (cmd *CommandsInfoCmd) Result() (map[string]*CommandInfo, error)
func (*CommandsInfoCmd) SetFirstKeyPos ¶
func (cmd *CommandsInfoCmd) SetFirstKeyPos(keyPos int8)
func (*CommandsInfoCmd) SetVal ¶
func (cmd *CommandsInfoCmd) SetVal(val map[string]*CommandInfo)
func (*CommandsInfoCmd) String ¶
func (cmd *CommandsInfoCmd) String() string
func (*CommandsInfoCmd) Val ¶
func (cmd *CommandsInfoCmd) Val() map[string]*CommandInfo
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn represents a single Ssdb connection rather than a pool of connections. Prefer running commands from Client unless there is a specific need for a continuous single Ssdb connection.
Example ¶
package main import ( "context" "github.com/ssdb-go/ssdb" ) var ( ctx = context.Background() sdb *ssdb.Client ) func main() { conn := sdb.Conn() err := conn.ClientSetName(ctx, "foobar").Err() if err != nil { panic(err) } // Open other connections. for i := 0; i < 10; i++ { go sdb.Ping(ctx) } }
Output: foobar
type Error ¶
type Error interface { error // SsdbError is a no-op function but // serves to distinguish types that are Ssdb // errors from ordinary errors: a type is a // Ssdb error if it has a SsdbError method. SsdbError() }
type Limiter ¶
type Limiter interface { // Allow returns nil if operation is allowed or an error otherwise. // If operation is allowed client must ReportResult of the operation // whether it is a success or a failure. Allow() error // ReportResult reports the result of the previously allowed operation. // nil indicates a success, non-nil error usually indicates a failure. ReportResult(result error) }
Limiter is the interface of a rate limiter or a circuit breaker.
type Options ¶
type Options struct { // The network type, either tcp or unix. // Default is tcp. Network string // host:port address. Addr string // Dialer creates new network connection and has priority over // Network and Addr options. Dialer func(ctx context.Context, network, addr string) (net.Conn, error) // Hook that is called when new connection is established. OnConnect func(ctx context.Context, cn *Conn) error // Use the specified Username to authenticate the current connection // with one of the connections defined in the ACL list when connecting // to a ssdb 6.0 instance, or greater, that is using the ssdb ACL system. Username string // Optional password. Must match the password specified in the // requirepass server configuration option (if connecting to a ssdb 5.0 instance, or lower), // or the User Password when connecting to a ssdb 6.0 instance, or greater, // that is using the ssdb ACL system. Password string // CredentialsProvider allows the username and password to be updated // before reconnecting. It should return the current username and password. CredentialsProvider func() (username string, password string) // Database to be selected after connecting to the server. DB int // Maximum number of retries before giving up. // Default is 3 retries; -1 (not 0) disables retries. MaxRetries int // Minimum backoff between each retry. // Default is 8 milliseconds; -1 disables backoff. MinRetryBackoff time.Duration // Maximum backoff between each retry. // Default is 512 milliseconds; -1 disables backoff. MaxRetryBackoff time.Duration // Dial timeout for establishing new connections. // Default is 5 seconds. DialTimeout time.Duration // Timeout for socket reads. If reached, commands will fail // with a timeout instead of blocking. Use value -1 for no timeout and 0 for default. // Default is 3 seconds. ReadTimeout time.Duration // Timeout for socket writes. If reached, commands will fail // with a timeout instead of blocking. // Default is ReadTimeout. WriteTimeout time.Duration // Type of connection pool. // true for FIFO pool, false for LIFO pool. // Note that fifo has higher overhead compared to lifo. PoolFIFO bool // Maximum number of socket connections. // Default is 10 connections per every available CPU as reported by runtime.GOMAXPROCS. PoolSize int // Amount of time client waits for connection if all connections // are busy before returning an error. // Default is ReadTimeout + 1 second. PoolTimeout time.Duration // Minimum number of idle connections which is useful when establishing // new connection is slow. MinIdleConns int // Maximum number of idle connections. MaxIdleConns int // Amount of time after which client closes idle connections. // Should be less than server's timeout. // Default is 5 minutes. -1 disables idle timeout check. ConnMaxIdleTime time.Duration // Connection age at which client retires (closes) the connection. // Default is to not close aged connections. ConnMaxLifetime time.Duration // TLS Config to use. When set TLS will be negotiated. TLSConfig *tls.Config // Limiter interface used to implemented circuit breaker or rate limiter. Limiter Limiter // contains filtered or unexported fields }
Options keeps the settings to setup ssdb connection.
func ParseURL ¶
ParseURL parses an URL into Options that can be used to connect to ssdb. Scheme is required. There are two connection types: by tcp socket and by unix socket. Tcp connection:
ssdb://<user>:<password>@<host>:<port>/<db_number>
Unix connection:
unix://<user>:<password>@</path/to/ssdb.sock>?db=<db_number>
Most Option fields can be set using query parameters, with the following restrictions:
- field names are mapped using snake-case conversion: to set MaxRetries, use max_retries
- only scalar type fields are supported (bool, int, time.Duration)
- for time.Duration fields, values must be a valid input for time.ParseDuration(); additionally a plain integer as value (i.e. without unit) is intepreted as seconds
- to disable a duration field, use value less than or equal to 0; to use the default value, leave the value blank or remove the parameter
- only the last value is interpreted if a parameter is given multiple times
- fields "network", "addr", "username" and "password" can only be set using other URL attributes (scheme, host, userinfo, resp.), query paremeters using these names will be treated as unknown parameters
- unknown parameter names will result in an error
Examples:
ssdb://user:password@localhost:6789/3?dial_timeout=3&db=1&read_timeout=6s&max_retries=2 is equivalent to: &Options{ Network: "tcp", Addr: "localhost:6789", DB: 1, // path "/3" was overridden by "&db=1" DialTimeout: 3 * time.Second, // no time unit = seconds ReadTimeout: 6 * time.Second, MaxRetries: 2, }
Example ¶
package main import ( "context" "fmt" "time" "github.com/ssdb-go/ssdb" ) var sdb *ssdb.Client func init() { sdb = ssdb.NewClient(&ssdb.Options{ Addr: ":8888", DialTimeout: 10 * time.Second, ReadTimeout: 30 * time.Second, WriteTimeout: 30 * time.Second, PoolSize: 10, PoolTimeout: 30 * time.Second, }) } func main() { opt, err := ssdb.ParseURL("ssdb://:qwerty@localhost:8888/1?dial_timeout=5s") if err != nil { panic(err) } fmt.Println("addr is", opt.Addr) fmt.Println("db is", opt.DB) fmt.Println("password is", opt.Password) fmt.Println("dial timeout is", opt.DialTimeout) // Create client as usually. _ = ssdb.NewClient(opt) }
Output: addr is localhost:8888 db is 1 password is qwerty dial timeout is 5s
type Pipeline ¶
type Pipeline struct {
// contains filtered or unexported fields
}
Pipeline implements pipelining as described in http://ssdb.io/topics/pipelining. It's safe for concurrent use by multiple goroutines.
Example (Instrumentation) ¶
sdb := ssdb.NewClient(&ssdb.Options{ Addr: ":8888", }) sdb.AddHook(ssdbHook{}) sdb.Pipelined(ctx, func(pipe ssdb.Pipeliner) error { pipe.Ping(ctx) pipe.Ping(ctx) return nil })
Output: pipeline starting processing: [ping: ping: ] pipeline finished processing: [ping: PONG ping: PONG]
func (Pipeline) AuthACL ¶
AuthACL Perform an AUTH command, using the given user and pass. Should be used to authenticate the current connection with one of the connections defined in the ACL list when connecting to a ssdb 6.0 instance, or greater, that is using the ssdb ACL system.
func (Pipeline) ClientSetName ¶
ClientSetName assigns a name to the connection.
func (Pipeline) DBSize ¶
------------------------------------------------------------------------------
func (*Pipeline) Discard ¶
func (c *Pipeline) Discard()
Discard resets the pipeline and discards queued commands.
func (*Pipeline) Exec ¶
Exec executes all previously queued commands using one client-server roundtrip.
Exec always returns list of commands and error of the first failed command if any.
func (*Pipeline) TxPipeline ¶
type Pipeliner ¶
type Pipeliner interface { StatefulCmdable Len() int Do(ctx context.Context, args ...interface{}) *Cmd Process(ctx context.Context, cmd Cmder) error Discard() Exec(ctx context.Context) ([]Cmder, error) }
Pipeliner is an mechanism to realise Ssdb Pipeline technique.
Pipelining is a technique to extremely speed up processing by packing operations to batches, send them at once to Ssdb and read a replies in a singe step.
Pay attention, that Pipeline is not a transaction, so you can get unexpected results in case of big pipelines and small read/write timeouts. Ssdb client has retransmission logic in case of timeouts, pipeline can be retransmitted and commands can be executed more then once. To avoid this: it is good idea to use reasonable bigger read/write timeouts depends of your batch size and/or use TxPipeline.
type ScanIterator ¶
type ScanIterator struct {
// contains filtered or unexported fields
}
ScanIterator is used to incrementally iterate over a collection of elements.
func (*ScanIterator) Err ¶
func (it *ScanIterator) Err() error
Err returns the last iterator error, if any.
func (*ScanIterator) Next ¶
func (it *ScanIterator) Next(ctx context.Context) bool
Next advances the cursor and returns true if more values can be read.
func (*ScanIterator) Val ¶
func (it *ScanIterator) Val() string
Val returns the key/field at the current cursor position.
type SlowLogCmd ¶
type SlowLogCmd struct {
// contains filtered or unexported fields
}
func NewSlowLogCmd ¶
func NewSlowLogCmd(ctx context.Context, args ...interface{}) *SlowLogCmd
func (*SlowLogCmd) Result ¶
func (cmd *SlowLogCmd) Result() ([]SlowLog, error)
func (*SlowLogCmd) SetFirstKeyPos ¶
func (cmd *SlowLogCmd) SetFirstKeyPos(keyPos int8)
func (*SlowLogCmd) SetVal ¶
func (cmd *SlowLogCmd) SetVal(val []SlowLog)
func (*SlowLogCmd) String ¶
func (cmd *SlowLogCmd) String() string
func (*SlowLogCmd) Val ¶
func (cmd *SlowLogCmd) Val() []SlowLog