gredis

package
v1.16.9 Latest Latest
Warning

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

Go to latest
Published: May 30, 2022 License: MIT Imports: 21 Imported by: 40

Documentation

Overview

Package gredis provides convenient client for redis server.

Redis Client.

Redis Commands Official: https://redis.io/commands

Redis Chinese Documentation: http://redisdoc.com/

Example (AutoMarshalUnmarshalMap)
package main

import (
	"fmt"
	"github.com/gogf/gf/container/gvar"
	"github.com/gogf/gf/frame/g"
)

func main() {
	var (
		err    error
		result *gvar.Var
		key    = "user"
		data   = g.Map{
			"id":   10000,
			"name": "john",
		}
	)
	_, err = g.Redis().Do("SET", key, data)
	if err != nil {
		panic(err)
	}
	result, err = g.Redis().DoVar("GET", key)
	if err != nil {
		panic(err)
	}
	fmt.Println(result.Map())
}
Output:

Example (AutoMarshalUnmarshalStruct)
package main

import (
	"fmt"
	"github.com/gogf/gf/container/gvar"
	"github.com/gogf/gf/frame/g"
)

func main() {
	type User struct {
		Id   int
		Name string
	}
	var (
		err    error
		result *gvar.Var
		key    = "user"
		user   = &User{
			Id:   10000,
			Name: "john",
		}
	)

	_, err = g.Redis().Do("SET", key, user)
	if err != nil {
		panic(err)
	}
	result, err = g.Redis().DoVar("GET", key)
	if err != nil {
		panic(err)
	}

	var user2 *User
	if err = result.Struct(&user2); err != nil {
		panic(err)
	}
	fmt.Println(user2.Id, user2.Name)
}
Output:

Example (AutoMarshalUnmarshalStructSlice)
package main

import (
	"fmt"
	"github.com/gogf/gf/container/gvar"
	"github.com/gogf/gf/frame/g"
)

func main() {
	type User struct {
		Id   int
		Name string
	}
	var (
		err    error
		result *gvar.Var
		key    = "user-slice"
		users1 = []User{
			{
				Id:   1,
				Name: "john1",
			},
			{
				Id:   2,
				Name: "john2",
			},
		}
	)

	_, err = g.Redis().Do("SET", key, users1)
	if err != nil {
		panic(err)
	}
	result, err = g.Redis().DoVar("GET", key)
	if err != nil {
		panic(err)
	}

	var users2 []User
	if err = result.Structs(&users2); err != nil {
		panic(err)
	}
	fmt.Println(users2)
}
Output:

Example (HMSet_Map)
package main

import (
	"fmt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gutil"
)

func main() {
	var (
		key  = "user_100"
		data = g.Map{
			"name":  "gf",
			"sex":   0,
			"score": 100,
		}
	)
	_, err := g.Redis().Do("HMSET", append(g.Slice{key}, gutil.MapToSlice(data)...)...)
	if err != nil {
		g.Log().Fatal(err)
	}
	v, err := g.Redis().DoVar("HMGET", key, "name")
	if err != nil {
		g.Log().Fatal(err)
	}
	fmt.Println(v.Slice())

	// May Output:
	// [gf]
}
Output:

Example (HMSet_Struct)
package main

import (
	"fmt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gutil"
)

func main() {
	type User struct {
		Name  string `json:"name"`
		Sex   int    `json:"sex"`
		Score int    `json:"score"`
	}
	var (
		key  = "user_100"
		data = &User{
			Name:  "gf",
			Sex:   0,
			Score: 100,
		}
	)
	_, err := g.Redis().Do("HMSET", append(g.Slice{key}, gutil.StructToSlice(data)...)...)
	if err != nil {
		g.Log().Fatal(err)
	}
	v, err := g.Redis().DoVar("HMGET", key, "name")
	if err != nil {
		g.Log().Fatal(err)
	}
	fmt.Println(v.Slice())

	// May Output:
	// ["gf"]
}
Output:

Example (HSet)
package main

import (
	"fmt"
	"github.com/gogf/gf/container/gvar"
	"github.com/gogf/gf/frame/g"
)

func main() {
	var (
		err    error
		result *gvar.Var
		key    = "user"
	)
	_, err = g.Redis().Do("HSET", key, "id", 10000)
	if err != nil {
		panic(err)
	}
	_, err = g.Redis().Do("HSET", key, "name", "john")
	if err != nil {
		panic(err)
	}
	result, err = g.Redis().DoVar("HGETALL", key)
	if err != nil {
		panic(err)
	}
	fmt.Println(result.Map())

	// May Output:
	// map[id:10000 name:john]
}
Output:

Index

Examples

Constants

View Source
const (
	DefaultGroupName = "default" // Default configuration group name.
	DefaultRedisPort = 6379      // Default redis port configuration if not passed.
)

Variables

This section is empty.

Functions

func ClearConfig

func ClearConfig()

ClearConfig removes all configurations and instances of redis.

func RemoveConfig

func RemoveConfig(name ...string)

RemoveConfig removes the global configuration with specified group. If <name> is not passed, it removes configuration of the default group name.

func SetConfig

func SetConfig(config *Config, name ...string)

SetConfig sets the global configuration for specified group. If <name> is not passed, it sets configuration for the default group name.

func SetConfigByStr

func SetConfigByStr(str string, name ...string) error

SetConfigByStr sets the global configuration for specified group with string. If <name> is not passed, it sets configuration for the default group name.

Types

type Config

type Config struct {
	Host            string        `json:"host"`
	Port            int           `json:"port"`
	Db              int           `json:"db"`
	Pass            string        `json:"pass"`            // Password for AUTH.
	MaxIdle         int           `json:"maxIdle"`         // Maximum number of connections allowed to be idle (default is 10)
	MaxActive       int           `json:"maxActive"`       // Maximum number of connections limit (default is 0 means no limit).
	IdleTimeout     time.Duration `json:"idleTimeout"`     // Maximum idle time for connection (default is 10 seconds, not allowed to be set to 0)
	MaxConnLifetime time.Duration `json:"maxConnLifetime"` // Maximum lifetime of the connection (default is 30 seconds, not allowed to be set to 0)
	ConnectTimeout  time.Duration `json:"connectTimeout"`  // Dial connection timeout.
	TLS             bool          `json:"tls"`             // Specifies the config to use when a TLS connection is dialed.
	TLSSkipVerify   bool          `json:"tlsSkipVerify"`   // Disables server name verification when connecting over TLS.
}

Config is redis configuration.

func ConfigFromStr

func ConfigFromStr(str string) (config *Config, err error)

ConfigFromStr parses and returns config from given str. Eg: host:port[,db,pass?maxIdle=x&maxActive=x&idleTimeout=x&maxConnLifetime=x]

func GetConfig

func GetConfig(name ...string) (config *Config, ok bool)

GetConfig returns the global configuration with specified group name. If <name> is not passed, it returns configuration of the default group name.

type Conn

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

Conn is redis connection.

func (*Conn) Ctx added in v1.15.2

func (c *Conn) Ctx(ctx context.Context) *Conn

Ctx is a channing function which sets the context for next operation.

func (*Conn) Do added in v1.13.0

func (c *Conn) Do(commandName string, args ...interface{}) (reply interface{}, err error)

Do sends a command to the server and returns the received reply. It uses json.Marshal for struct/slice/map type values before committing them to redis.

func (*Conn) DoVar

func (c *Conn) DoVar(commandName string, args ...interface{}) (*gvar.Var, error)

DoVar retrieves and returns the result from command as gvar.Var.

func (*Conn) DoVarWithTimeout added in v1.13.3

func (c *Conn) DoVarWithTimeout(timeout time.Duration, commandName string, args ...interface{}) (*gvar.Var, error)

DoVarWithTimeout retrieves and returns the result from command as gvar.Var. The timeout overrides the read timeout set when dialing the connection.

func (*Conn) DoWithTimeout added in v1.13.3

func (c *Conn) DoWithTimeout(timeout time.Duration, commandName string, args ...interface{}) (reply interface{}, err error)

DoWithTimeout sends a command to the server and returns the received reply. The timeout overrides the read timeout set when dialing the connection.

func (*Conn) ReceiveVar

func (c *Conn) ReceiveVar() (*gvar.Var, error)

ReceiveVar receives a single reply as gvar.Var from the Redis server.

func (*Conn) ReceiveVarWithTimeout added in v1.13.3

func (c *Conn) ReceiveVarWithTimeout(timeout time.Duration) (*gvar.Var, error)

ReceiveVarWithTimeout receives a single reply as gvar.Var from the Redis server. The timeout overrides the read timeout set when dialing the connection.

type PoolStats

type PoolStats struct {
	redis.PoolStats
}

PoolStats is statistics of redis connection pool.

type Redis

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

Redis client.

func Instance

func Instance(name ...string) *Redis

Instance returns an instance of redis client with specified group. The <name> param is unnecessary, if <name> is not passed, it returns a redis instance with default configuration group.

func New

func New(config *Config) *Redis

New creates a redis client object with given configuration. Redis client maintains a connection pool automatically.

func NewFromStr

func NewFromStr(str string) (*Redis, error)

NewFromStr creates a redis client object with given configuration string. Redis client maintains a connection pool automatically. The parameter <str> like: 127.0.0.1:6379,0 127.0.0.1:6379,0,password

func (*Redis) Clone added in v1.15.2

func (r *Redis) Clone() *Redis

Clone clones and returns a new Redis object, which is a shallow copy of current one.

func (*Redis) Close

func (r *Redis) Close() error

Close closes the redis connection pool, it will release all connections reserved by this pool. It is not necessary to call Close manually.

func (*Redis) Conn

func (r *Redis) Conn() *Conn

Conn returns a raw underlying connection object, which expose more methods to communicate with server. **You should call Close function manually if you do not use this connection any further.**

func (*Redis) Ctx added in v1.15.2

func (r *Redis) Ctx(ctx context.Context) *Redis

Ctx is a channing function which sets the context for next operation.

func (*Redis) Do

func (r *Redis) Do(commandName string, args ...interface{}) (interface{}, error)

Do sends a command to the server and returns the received reply. Do automatically get a connection from pool, and close it when the reply received. It does not really "close" the connection, but drops it back to the connection pool.

func (*Redis) DoVar

func (r *Redis) DoVar(commandName string, args ...interface{}) (*gvar.Var, error)

DoVar returns value from Do as gvar.Var.

func (*Redis) DoVarWithTimeout added in v1.13.3

func (r *Redis) DoVarWithTimeout(timeout time.Duration, commandName string, args ...interface{}) (*gvar.Var, error)

DoVarWithTimeout returns value from Do as gvar.Var. The timeout overrides the read timeout set when dialing the connection.

func (*Redis) DoWithTimeout added in v1.13.3

func (r *Redis) DoWithTimeout(timeout time.Duration, commandName string, args ...interface{}) (interface{}, error)

DoWithTimeout sends a command to the server and returns the received reply. The timeout overrides the read timeout set when dialing the connection.

func (*Redis) GetConn

func (r *Redis) GetConn() *Conn

GetConn is alias of Conn, see Conn. Deprecated, use Conn instead.

func (*Redis) SetIdleTimeout

func (r *Redis) SetIdleTimeout(value time.Duration)

SetIdleTimeout sets the IdleTimeout attribute of the connection pool. It closes connections after remaining idle for this duration. If the value is zero, then idle connections are not closed. Applications should set the timeout to a value less than the server's timeout.

func (*Redis) SetMaxActive

func (r *Redis) SetMaxActive(value int)

SetMaxActive sets the maximum number of connections allocated by the pool at a given time. When zero, there is no limit on the number of connections in the pool.

Note that if the pool is at the MaxActive limit, then all the operations will wait for a connection to be returned to the pool before returning.

func (*Redis) SetMaxConnLifetime

func (r *Redis) SetMaxConnLifetime(value time.Duration)

SetMaxConnLifetime sets the MaxConnLifetime attribute of the connection pool. It closes connections older than this duration. If the value is zero, then the pool does not close connections based on age.

func (*Redis) SetMaxIdle

func (r *Redis) SetMaxIdle(value int)

SetMaxIdle sets the maximum number of idle connections in the pool.

func (*Redis) Stats

func (r *Redis) Stats() *PoolStats

Stats returns pool's statistics.

Jump to

Keyboard shortcuts

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