Go Redis Client

xredis Build Status Go Report Card GoDoc License: MIT

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")))
}
Owner
Raed Shomali
A Software Engineer by Profession, a Photographer by Talent and a Joker by Nature.
Raed Shomali
Similar Resources

Redisx: a library of Go utilities built on the redigo redis client library

redisx redisx is a library of Go utilities built on the redigo redis client libr

Dec 24, 2021

Redis client for Golang

Redis client for Golang

Redis client for Golang To ask questions, join Discord or use Discussions. Newsl

Dec 23, 2021

Redis client for Golang

Redis client for Golang

Redis client for Golang Discussions. Newsletter to get latest updates. Documentation Reference Examples RealWorld example app Other projects you may l

Dec 30, 2021

High-performance framework for building redis-protocol compatible TCP servers/services

Redeo The high-performance Swiss Army Knife for building redis-protocol compatible servers/services. Parts This repository is organised into multiple

Jan 4, 2023

Simple key-value store abstraction and implementations for Go (Redis, Consul, etcd, bbolt, BadgerDB, LevelDB, Memcached, DynamoDB, S3, PostgreSQL, MongoDB, CockroachDB and many more)

gokv Simple key-value store abstraction and implementations for Go Contents Features Simple interface Implementations Value types Marshal formats Road

Dec 24, 2022

Redis Sorted Sets Benchmark

redis-zbench-go Redis Sorted Sets Benchmark Overview This repo contains code to trigger load ( ZADD ) or query (ZRANGEBYLEX key min max) benchmarks, w

May 18, 2021

Use Redis' MONITOR to draw things in a terminal

Use Redis' MONITOR to draw things in a terminal

Redis Top Redistop uses MONITOR to watch Redis commands and shows per command and per host statistics. Because MONITOR streams back all commands, its

Aug 30, 2022

Examples and code to assign a name to your MongoDB, MySQL, PostgreSQL, RabbitMQ, and redis connection.

Examples and code to assign a name to your MongoDB, MySQL, PostgreSQL, RabbitMQ, and redis connection.

your connection deserves a name 👀 When your app interacts with an external system, assign a name to the connection. An external system in this contex

Dec 14, 2022

redis protocol server for go.

redigosrv what redis server侧的golang版本实现。 why 作为后端RD,你开发的,维护的最多的应该就是你的server,作为服务的提供方来说,想要和客户端进行有效的交互,首先要要能理解信息的含义,因此一套通信协议是必须的。 为什么选择redis协议,应用层有很多成熟的

Nov 30, 2021
GoBigdis is a persistent database that implements the Redis server protocol. Any Redis client can interface with it and start to use it right away.

GoBigdis GoBigdis is a persistent database that implements the Redis server protocol. Any Redis client can interface with it and start to use it right

Apr 27, 2022
Bxd redis benchmark - Redis benchmark tool for golang

使用 redis benchmark 工具, 测试 10 20 50 100 200 1k 5k 字节 value 大小,redis get set 性能。 r

Jan 22, 2022
redis client implement by golang, inspired by jedis.

godis redis client implement by golang, refers to jedis. this library implements most of redis command, include normal redis command, cluster command,

Dec 6, 2022
Go client for Redis

Redigo Redigo is a Go client for the Redis database. Features A Print-like API with support for all Redis commands. Pipelining, including pipelined tr

Jan 1, 2023
Type-safe Redis client for Golang

Redis client for Golang ❤️ Uptrace.dev - distributed traces, logs, and errors in one place Join Discord to ask questions. Documentation Reference Exam

Jan 1, 2023
Go Redis Client

xredis 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 l

Sep 26, 2022
godis - an old Redis client for Go

godis Implements a few database clients for Redis. There is a stable client and an experimental client, redis and exp, respectively. To use any of the

Apr 16, 2022
Google Go Client and Connectors for Redis

Go-Redis Go Clients and Connectors for Redis. The initial release provides the interface and implementation supporting the (~) full set of current Red

Oct 25, 2022
Redis client library for Go

go-redis go-redis is a Redis client library for the Go programming language. It's built on the skeleton of gomemcache. It is safe to use by multiple g

Nov 8, 2022
Type-safe Redis client for Golang

Redis client for Golang ❤️ Uptrace.dev - distributed traces, logs, and errors in one place Join Discord to ask questions. Documentation Reference Exam

Jan 4, 2023