xredis

package module
v0.0.0-...-0b54a6b Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2019 License: MIT Imports: 8 Imported by: 7

README

xredis Build Status Go Report Card GoDoc

Built on top of github.com/garyburd/redigo with the idea to simplify creating a Redis client, provide type safe calls and encapsulate the low level details to easily integrate with Redis.

Features

  • Type safe client
  • Easy to setup using
    • Default client
    • Custom client via set options
    • redigo's redis.Pool
  • Connection pool provided automatically
  • Support for Redis Sentinel
    • Writes go to the Master
    • Reads go to the Slaves. Falls back on Master if none are available.
  • Supports the following Redis commands
    • ECHO, INFO, PING, FLUSH, FLUSHALL, EXPIRE, APPEND
    • SET, SETEX, SETNX, GET, DEL, EXISTS, KEYS, SCAN, GETRANGE, SETRANGE
    • HSET, HGET, HGETALL, HDEL, HEXISTS, HKEYS, HSCAN
    • INCR, INCRBY, INCRBYFLOAT, DECR, DECRBY, DECRBYFLOAT
    • HINCR, HINCRBY, HINCRBYFLOAT, HDECR, HDECRBY, HDECRBYFLOAT
    • More coming soon
  • Full access to Redigo's API github.com/garyburd/redigo

Dependencies

Examples

Example 1

Using DefaultClient to create a redis client with default options

package main

import (
	"fmt"
	"github.com/shomali11/xredis"
)

func main() {
	client := xredis.DefaultClient()
	defer client.Close()

	fmt.Println(client.Ping()) // PONG <nil>
}

List of default options

defaultHost                  = "localhost"
defaultPort                  = 6379
defaultPassword              = ""
defaultDatabase              = 0
defaultNetwork               = "tcp"
defaultConnectTimeout        = time.Second
defaultWriteTimeout          = time.Second
defaultReadTimeout           = time.Second
defaultConnectionIdleTimeout = 240 * time.Second
defaultConnectionMaxIdle     = 100
defaultConnectionMaxActive   = 10000
defaultConnectionWait        = false
defaultTlsConfig             = nil
defaultTlsSkipVerify         = false
defaultTestOnBorrowTimeout   = time.Minute

Example 2

Using SetupClient to create a redis client using provided options

package main

import (
	"fmt"
	"github.com/shomali11/xredis"
)

func main() {
	options := &xredis.Options{
		Host: "localhost",
		Port: 6379,
	}

	client := xredis.SetupClient(options)
	defer client.Close()

	fmt.Println(client.Ping()) // PONG <nil>
}

Available options to set

type Options struct {
	Host                  string
	Port                  int
	Password              string
	Database              int
	Network               string
	ConnectTimeout        time.Duration
	WriteTimeout          time.Duration
	ReadTimeout           time.Duration
	ConnectionIdleTimeout time.Duration
	ConnectionMaxIdle     int
	ConnectionMaxActive   int
	ConnectionWait        bool
	TlsConfig             *tls.Config
	TlsSkipVerify         bool
	TestOnBorrowPeriod    time.Duration
}

Example 3

Using SetupSentinelClient to create a redis sentinel client using provided options

package main

import (
	"fmt"
	"github.com/shomali11/xredis"
)

func main() {
	options := &xredis.SentinelOptions{
		Addresses:  []string{"localhost:26379"},
		MasterName: "master",
	}

	client := xredis.SetupSentinelClient(options)
	defer client.Close()

	fmt.Println(client.Ping()) // PONG <nil>
}

Available options to set

type SentinelOptions struct {
	Addresses             []string
	MasterName            string
	Password              string
	Database              int
	Network               string
	ConnectTimeout        time.Duration
	WriteTimeout          time.Duration
	ReadTimeout           time.Duration
	ConnectionIdleTimeout time.Duration
	ConnectionMaxIdle     int
	ConnectionMaxActive   int
	ConnectionWait        bool
	TlsConfig             *tls.Config
	TlsSkipVerify         bool
}

Example 4

Using NewClient to create a redis client using redigo's redis.Pool

package main

import (
	"fmt"
	"github.com/garyburd/redigo/redis"
	"github.com/shomali11/xredis"
)

func main() {
	pool := &redis.Pool{
		Dial: func() (redis.Conn, error) {
			return redis.Dial("tcp", "localhost:6379")
		},
	}

	client := xredis.NewClient(pool)
	defer client.Close()

	fmt.Println(client.Ping()) // PONG <nil>
}

Example 5

Using the Ping, Echo & Info commands to ping, echo messages and return redis' information and statistics

package main

import (
	"fmt"
	"github.com/shomali11/xredis"
)

func main() {
	client := xredis.DefaultClient()
	defer client.Close()

	fmt.Println(client.Ping())         // PONG <nil>
	fmt.Println(client.Echo("Hello"))  // Hello <nil>
	fmt.Println(client.FlushDb())      // <nil>
	fmt.Println(client.FlushAll())     // <nil>
	fmt.Println(client.Info())         
}

Example 6

Using the Set, Keys, Get, Exists, Expire, Append, GetRange, SetRange and Del commands to show how to set, get and delete keys and values. Note that the Get returns 3 values, a string result, a bool that determines whether the key exists and an error

package main

import (
	"fmt"
	"github.com/shomali11/xredis"
)

func main() {
	client := xredis.DefaultClient()
	defer client.Close()

	fmt.Println(client.Set("name", "Raed Shomali")) // true <nil>
	fmt.Println(client.SetNx("name", "Hello"))      // false <nil>
	fmt.Println(client.SetEx("id", "10", 1))        // true <nil>
	fmt.Println(client.Expire("name", 1))           // true <nil>
	fmt.Println(client.Expire("unknown", 1))        // false <nil>
	fmt.Println(client.Keys("*"))                   // [id name] <nil>
	fmt.Println(client.Get("name"))                 // "Raed Shomali" true <nil>
	fmt.Println(client.Exists("name"))              // true <nil>
	fmt.Println(client.Del("name"))                 // 1 <nil>
	fmt.Println(client.Exists("name"))              // false <nil>
	fmt.Println(client.Get("name"))                 // "" false <nil>
	fmt.Println(client.Del("name"))                 // 0 <nil>
	fmt.Println(client.Append("name", "a"))         // 1 <nil>
	fmt.Println(client.Append("name", "b"))         // 2 <nil>
	fmt.Println(client.Append("name", "c"))         // 3 <nil>
	fmt.Println(client.Get("name"))                 // "abc" true <nil>
	fmt.Println(client.GetRange("name", 0 , 1))     // "ab" <nil>
	fmt.Println(client.SetRange("name", 2, "xyz"))  // 5 <nil>
	fmt.Println(client.Get("name"))                 // "abxyz" <nil>
	fmt.Println(client.Scan(0, "*"))                // 0 [name id] <nil>
	fmt.Println(client.Del("id", "name"))           // 2 <nil>
}

Example 7

Using the Incr, IncrBy, IncrByFloat, Decr, DecrBy, DecrByFloat commands, we can increment and decrement a key's value

package main

import (
	"fmt"
	"github.com/shomali11/xredis"
)

func main() {
	client := xredis.DefaultClient()
	defer client.Close()

	fmt.Println(client.Set("integer", "10"))       // true <nil>
	fmt.Println(client.Set("float", "5.5"))        // true <nil>

	fmt.Println(client.Get("integer"))             // 10 true <nil>
	fmt.Println(client.Get("float"))               // 5.5 true <nil>

	fmt.Println(client.Incr("integer"))            // 11 <nil>
	fmt.Println(client.IncrBy("integer", 10))      // 21 <nil>
	fmt.Println(client.DecrBy("integer", 5))       // 16 <nil>
	fmt.Println(client.Decr("integer"))            // 15 <nil>

	fmt.Println(client.IncrByFloat("float", 3.3))  // 8.8 <nil>
	fmt.Println(client.DecrByFloat("float", 1.1))  // 7.7 <nil>

	fmt.Println(client.Get("integer"))             // 15 true <nil>
	fmt.Println(client.Get("float"))               // 7.7 true <nil>

	fmt.Println(client.Del("integer", "float"))    // 2 <nil>
}

Example 8

Using the HSet, HKeys, HGet, HGetAll, HExists and HDel commands to show how to set, get and delete hash keys, fields and values. Note that the HGetAll returns 2 values, a map[string]string result and an error

package main

import (
	"fmt"
	"github.com/shomali11/xredis"
)

func main() {
	client := xredis.DefaultClient()
	defer client.Close()

	fmt.Println(client.HSet("hash", "name", "Raed Shomali")) // true <nil>
	fmt.Println(client.HSet("hash", "sport", "Football"))    // true <nil>
	fmt.Println(client.HKeys("hash"))                        // [name sport] <nil>
	fmt.Println(client.HScan("hash", 0, "*"))                // 0 [name Raed Shomali sport Football] <nil>
	fmt.Println(client.HGet("hash", "name"))                 // "Raed Shomali" true <nil>
	fmt.Println(client.HGetAll("hash"))                      // map[name:Raed Shomali sport:Football] <nil>
	fmt.Println(client.HExists("hash", "name"))              // true <nil>
	fmt.Println(client.HDel("hash", "name", "sport"))        // 2 <nil>
	fmt.Println(client.HGet("hash", "name"))                 // "" false <nil>
	fmt.Println(client.HExists("hash", "name"))              // false <nil>
	fmt.Println(client.HGetAll("hash"))                      // map[] nil
	fmt.Println(client.HDel("hash", "name"))                 // 0 <nil>
	fmt.Println(client.HKeys("hash"))                        // [] <nil>
}

Example 9

Using the HIncr, HIncrBy, HIncrByFloat,HDecr, HDecrBy and HDecrByFloat commands to show how to increment and decrement hash fields' values.

package main

import (
	"fmt"
	"github.com/shomali11/xredis"
)

func main() {
	client := xredis.DefaultClient()
	defer client.Close()

	fmt.Println(client.HSet("hash", "integer", "10"))       // true <nil>
	fmt.Println(client.HSet("hash", "float", "5.5"))        // true <nil>

	fmt.Println(client.HIncr("hash", "integer"))            // 11 <nil>
	fmt.Println(client.HIncrBy("hash", "integer", 10))      // 21 <nil>
	fmt.Println(client.HDecrBy("hash", "integer", 5))       // 16 <nil>
	fmt.Println(client.HDecr("hash", "integer"))            // 15 <nil>

	fmt.Println(client.HIncrByFloat("hash", "float", 3.3))  // 8.8 <nil>
	fmt.Println(client.HDecrByFloat("hash", "float", 1.1))  // 7.7 <nil>

	fmt.Println(client.HDel("hash", "integer", "float"))    // 2 <nil>
}

Example 10

Can't find the command you want? You have full access to redigo's API.

package main

import (
	"fmt"
	"github.com/garyburd/redigo/redis"
	"github.com/shomali11/xredis"
)

func main() {
	client := xredis.DefaultClient()
	defer client.Close()

	connection := client.GetConnection()
	defer connection.Close()

	fmt.Println(redis.String(connection.Do("INFO")))
}

Documentation

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 redis client

func DefaultClient

func DefaultClient() *Client

DefaultClient returns a client with default options

func NewClient

func NewClient(pool *redis.Pool) *Client

NewClient returns a client using provided redis.Pool

func SetupClient

func SetupClient(options *Options) *Client

SetupClient returns a client with provided options

func SetupSentinelClient

func SetupSentinelClient(options *SentinelOptions) *Client

SetupSentinelClient returns a client with provided options

func (*Client) Append

func (c *Client) Append(key string, value string) (int64, error)

Append to a key's value

func (*Client) Close

func (c *Client) Close() error

Close closes connections writePool

func (*Client) Decr

func (c *Client) Decr(key string) (int64, error)

Decr decrements the key's value

func (*Client) DecrBy

func (c *Client) DecrBy(key string, decrement int64) (int64, error)

DecrBy decrements the key's value by the decrement provided

func (*Client) DecrByFloat

func (c *Client) DecrByFloat(key string, decrement float64) (float64, error)

DecrByFloat decrements the key's value by the decrement provided

func (*Client) Del

func (c *Client) Del(keys ...string) (int64, error)

Del deletes keys

func (*Client) Echo

func (c *Client) Echo(message string) (string, error)

Echo echoes the message

func (*Client) Exists

func (c *Client) Exists(keys ...string) (bool, error)

Exists checks how many keys exist

func (*Client) Expire

func (c *Client) Expire(key string, timeout int64) (bool, error)

Expire sets a key's timeout in seconds

func (*Client) FlushAll

func (c *Client) FlushAll() error

FlushAll flushes the keys of all databases

func (*Client) FlushDb

func (c *Client) FlushDb() error

FlushDb flushes the keys of the current database

func (*Client) Get

func (c *Client) Get(key string) (string, bool, error)

Get retrieves a key's value

func (*Client) GetConnection

func (c *Client) GetConnection() redis.Conn

GetConnection gets a connection from the pool

func (*Client) GetRange

func (c *Client) GetRange(key string, start int, end int) (string, error)

GetRange to get a key's value's range

func (*Client) HDecr

func (c *Client) HDecr(key string, field string) (int64, error)

HDecr decrements the key's field's value

func (*Client) HDecrBy

func (c *Client) HDecrBy(key string, field string, decrement int64) (int64, error)

HDecrBy decrements the key's field's value by the decrement provided

func (*Client) HDecrByFloat

func (c *Client) HDecrByFloat(key string, field string, decrement float64) (float64, error)

HDecrByFloat decrements the key's field's value by the decrement provided

func (*Client) HDel

func (c *Client) HDel(key string, fields ...string) (int64, error)

HDel deletes a key's fields

func (*Client) HExists

func (c *Client) HExists(key string, field string) (bool, error)

HExists determine's a key's field's existence

func (*Client) HGet

func (c *Client) HGet(key string, field string) (string, bool, error)

HGet retrieves a key's field's value

func (*Client) HGetAll

func (c *Client) HGetAll(key string) (map[string]string, error)

HGetAll retrieves the key

func (*Client) HIncr

func (c *Client) HIncr(key string, field string) (int64, error)

HIncr increments the key's field's value

func (*Client) HIncrBy

func (c *Client) HIncrBy(key string, field string, increment int64) (int64, error)

HIncrBy increments the key's field's value by the increment provided

func (*Client) HIncrByFloat

func (c *Client) HIncrByFloat(key string, field string, increment float64) (float64, error)

HIncrByFloat increments the key's field's value by the increment provided

func (*Client) HKeys

func (c *Client) HKeys(key string) ([]string, error)

HKeys retrieves a hash's keys

func (*Client) HScan

func (c *Client) HScan(key string, startIndex int64, pattern string) (int64, []string, error)

HScan incrementally iterate over key's fields and values

func (*Client) HSet

func (c *Client) HSet(key string, field string, value string) (bool, error)

HSet sets a key's field/value pair

func (*Client) Incr

func (c *Client) Incr(key string) (int64, error)

Incr increments the key's value

func (*Client) IncrBy

func (c *Client) IncrBy(key string, increment int64) (int64, error)

IncrBy increments the key's value by the increment provided

func (*Client) IncrByFloat

func (c *Client) IncrByFloat(key string, increment float64) (float64, error)

IncrByFloat increments the key's value by the increment provided

func (*Client) Info

func (c *Client) Info() (string, error)

Info returns redis information and statistics

func (*Client) Keys

func (c *Client) Keys(pattern string) ([]string, error)

Keys retrieves keys that match a pattern

func (*Client) Ping

func (c *Client) Ping() (string, error)

Ping pings redis

func (*Client) Scan

func (c *Client) Scan(startIndex int64, pattern string) (int64, []string, error)

Scan incrementally iterate over keys

func (*Client) Set

func (c *Client) Set(key string, value string) (bool, error)

Set sets a key/value pair

func (*Client) SetEx

func (c *Client) SetEx(key string, value string, timeout int64) (bool, error)

SetEx sets a key/value pair with a timeout in seconds

func (*Client) SetNx

func (c *Client) SetNx(key string, value string) (bool, error)

SetNx sets a key/value pair if the key does not exist

func (*Client) SetRange

func (c *Client) SetRange(key string, start int, value string) (int64, error)

SetRange to set a key's value's range

type Options

type Options struct {
	Host                  string
	Port                  int
	Password              string
	Database              int
	Network               string
	ConnectTimeout        time.Duration
	WriteTimeout          time.Duration
	ReadTimeout           time.Duration
	ConnectionIdleTimeout time.Duration
	ConnectionMaxIdle     int
	ConnectionMaxActive   int
	ConnectionWait        bool
	TlsConfig             *tls.Config
	TlsSkipVerify         bool
	TestOnBorrowPeriod    time.Duration
}

Options contains redis options

func (*Options) GetAddress

func (o *Options) GetAddress() string

GetAddress returns address

func (*Options) GetConnectTimeout

func (o *Options) GetConnectTimeout() time.Duration

GetConnectTimeout returns connect timeout

func (*Options) GetConnectionIdleTimeout

func (o *Options) GetConnectionIdleTimeout() time.Duration

GetConnectionIdleTimeout returns connection idle timeout

func (*Options) GetConnectionMaxActive

func (o *Options) GetConnectionMaxActive() int

GetConnectionMaxActive returns connection max active

func (*Options) GetConnectionMaxIdle

func (o *Options) GetConnectionMaxIdle() int

GetConnectionMaxIdle returns connection max idle

func (*Options) GetConnectionWait

func (o *Options) GetConnectionWait() bool

GetConnectionWait returns connection wait

func (*Options) GetDatabase

func (o *Options) GetDatabase() int

GetDatabase returns database

func (*Options) GetHost

func (o *Options) GetHost() string

GetHost returns host

func (*Options) GetNetwork

func (o *Options) GetNetwork() string

GetNetwork returns network

func (*Options) GetPassword

func (o *Options) GetPassword() string

GetPassword returns password

func (*Options) GetPort

func (o *Options) GetPort() int

GetPort returns port

func (*Options) GetReadTimeout

func (o *Options) GetReadTimeout() time.Duration

GetReadTimeout returns read timeout

func (*Options) GetTestOnBorrowPeriod

func (o *Options) GetTestOnBorrowPeriod() time.Duration

GetTestOnBorrowPeriod return test on borrow period

func (*Options) GetTlsConfig

func (o *Options) GetTlsConfig() *tls.Config

GetTlsConfig returns tls config

func (*Options) GetTlsSkipVerify

func (o *Options) GetTlsSkipVerify() bool

GetTlsSkipVerify returns tls skip verify

func (*Options) GetWriteTimeout

func (o *Options) GetWriteTimeout() time.Duration

GetWriteTimeout returns write timeout

type SentinelOptions

type SentinelOptions struct {
	Addresses             []string
	MasterName            string
	Password              string
	Database              int
	Network               string
	ConnectTimeout        time.Duration
	WriteTimeout          time.Duration
	ReadTimeout           time.Duration
	ConnectionIdleTimeout time.Duration
	ConnectionMaxIdle     int
	ConnectionMaxActive   int
	ConnectionWait        bool
	TlsConfig             *tls.Config
	TlsSkipVerify         bool
	TestOnBorrowPeriod    time.Duration
}

SentinelOptions contains redis sentinel options

func (*SentinelOptions) GetAddresses

func (o *SentinelOptions) GetAddresses() []string

GetAddresses returns sentinel address

func (*SentinelOptions) GetConnectTimeout

func (o *SentinelOptions) GetConnectTimeout() time.Duration

GetConnectTimeout returns connect timeout

func (*SentinelOptions) GetConnectionIdleTimeout

func (o *SentinelOptions) GetConnectionIdleTimeout() time.Duration

GetConnectionIdleTimeout returns connection idle timeout

func (*SentinelOptions) GetConnectionMaxActive

func (o *SentinelOptions) GetConnectionMaxActive() int

GetConnectionMaxActive returns connection max active

func (*SentinelOptions) GetConnectionMaxIdle

func (o *SentinelOptions) GetConnectionMaxIdle() int

GetConnectionMaxIdle returns connection max idle

func (*SentinelOptions) GetConnectionWait

func (o *SentinelOptions) GetConnectionWait() bool

GetConnectionWait returns connection wait

func (*SentinelOptions) GetDatabase

func (o *SentinelOptions) GetDatabase() int

GetDatabase returns database

func (*SentinelOptions) GetMasterName

func (o *SentinelOptions) GetMasterName() string

GetMasterName returns master name

func (*SentinelOptions) GetNetwork

func (o *SentinelOptions) GetNetwork() string

GetNetwork returns network

func (*SentinelOptions) GetPassword

func (o *SentinelOptions) GetPassword() string

GetPassword returns password

func (*SentinelOptions) GetReadTimeout

func (o *SentinelOptions) GetReadTimeout() time.Duration

GetReadTimeout returns read timeout

func (*SentinelOptions) GetTestOnBorrowPeriod

func (o *SentinelOptions) GetTestOnBorrowPeriod() time.Duration

GetTestOnBorrowPeriod return test on borrow period

func (*SentinelOptions) GetTlsConfig

func (o *SentinelOptions) GetTlsConfig() *tls.Config

GetTlsConfig returns tls config

func (*SentinelOptions) GetTlsSkipVerify

func (o *SentinelOptions) GetTlsSkipVerify() bool

GetTlsSkipVerify returns tls skip verify

func (*SentinelOptions) GetWriteTimeout

func (o *SentinelOptions) GetWriteTimeout() time.Duration

GetWriteTimeout returns write timeout

Directories

Path Synopsis
examples
1
10
2
3
4
5
6
7
8
9

Jump to

Keyboard shortcuts

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