gredis

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2021 License: MIT Imports: 22 Imported by: 0

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 (
	"context"
	"fmt"

	"easyscdp.com/gogf/gf/container/gvar"
	"easyscdp.com/gogf/gf/frame/g"
)

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

Example (AutoMarshalUnmarshalStruct)
package main

import (
	"context"
	"fmt"

	"easyscdp.com/gogf/gf/container/gvar"
	"easyscdp.com/gogf/gf/frame/g"
)

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

	_, err = g.Redis().Do(ctx, "SET", key, user)
	if err != nil {
		panic(err)
	}
	result, err = g.Redis().Do(ctx, "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 (
	"context"
	"fmt"

	"easyscdp.com/gogf/gf/container/gvar"
	"easyscdp.com/gogf/gf/frame/g"
)

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

	_, err = g.Redis().Do(ctx, "SET", key, users1)
	if err != nil {
		panic(err)
	}
	result, err = g.Redis().Do(ctx, "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 (
	"context"
	"fmt"

	"easyscdp.com/gogf/gf/frame/g"
	"easyscdp.com/gogf/gf/util/gutil"
)

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

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

Example (HMSet_Struct)
package main

import (
	"context"
	"fmt"

	"easyscdp.com/gogf/gf/frame/g"
	"easyscdp.com/gogf/gf/util/gutil"
)

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

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

Example (HSet)
package main

import (
	"context"
	"fmt"

	"easyscdp.com/gogf/gf/container/gvar"
	"easyscdp.com/gogf/gf/frame/g"
)

func main() {
	var (
		err    error
		result *gvar.Var
		ctx    = context.Background()
		key    = "user"
	)
	_, err = g.Redis().Do(ctx, "HSET", key, "id", 10000)
	if err != nil {
		panic(err)
	}
	_, err = g.Redis().Do(ctx, "HSET", key, "name", "john")
	if err != nil {
		panic(err)
	}
	result, err = g.Redis().Do(ctx, "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.
)

Variables

This section is empty.

Functions

func ClearConfig

func ClearConfig()

ClearConfig removes all configurations 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 SetConfigByMap

func SetConfigByMap(m map[string]interface{}, name ...string) error

SetConfigByMap sets the global configuration for specified group with map. If `name` is not passed, it sets configuration for the default group name.

Types

type Adapter

type Adapter interface {
	// Conn retrieves and returns a connection object for continuous operations.
	// Note that you should call Close function manually if you do not use this connection any further.
	Conn(ctx context.Context) (conn Conn, err error)

	// Close closes current redis client, closes its connection pool and releases all its related resources.
	Close(ctx context.Context) (err error)
}

Adapter is an interface for universal redis operations.

type AdapterGoRedis

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

AdapterGoRedis is an implement of Adapter using go-redis.

func NewAdapterGoRedis

func NewAdapterGoRedis(config *Config) *AdapterGoRedis

NewAdapterGoRedis creates and returns a redis adapter using go-redis.

func (*AdapterGoRedis) Close

func (r *AdapterGoRedis) Close(ctx context.Context) error

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

func (*AdapterGoRedis) Conn

func (r *AdapterGoRedis) Conn(ctx context.Context) (Conn, error)

Conn retrieves and returns a connection object for continuous operations. Note that you should call Close function manually if you do not use this connection any further.

type Config

type Config struct {
	Address         string        `json:"address"`         // It supports single and cluster redis server. Multiple addresses joined with char ','. Eg: 192.168.1.1:6379, 192.168.1.2:6379.
	Db              int           `json:"db"`              // Redis db.
	Pass            string        `json:"pass"`            // Password for AUTH.
	MinIdle         int           `json:"minIdle"`         // Minimum number of connections allowed to be idle (default is 0)
	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).
	MaxConnLifetime time.Duration `json:"maxConnLifetime"` // Maximum lifetime of the connection (default is 30 seconds, not allowed to be set to 0)
	IdleTimeout     time.Duration `json:"idleTimeout"`     // Maximum idle time for connection (default is 10 seconds, not allowed to be set to 0)
	WaitTimeout     time.Duration `json:"waitTimeout"`     // Timed out duration waiting to get a connection from the connection pool.
	DialTimeout     time.Duration `json:"dialTimeout"`     // Dial connection timeout for TCP.
	ReadTimeout     time.Duration `json:"readTimeout"`     // Read timeout for TCP.
	WriteTimeout    time.Duration `json:"writeTimeout"`    // Write timeout for TCP.
	MasterName      string        `json:"masterName"`      // Used in Redis Sentinel mode.
	TLS             bool          `json:"tls"`             // Specifies whether TLS should be used when connecting to the server.
	TLSSkipVerify   bool          `json:"tlsSkipVerify"`   // Disables server name verification when connecting over TLS.
	TLSConfig       *tls.Config   `json:"-"`               // TLS Config to use. When set TLS will be negotiated.
}

Config is redis configuration.

func ConfigFromMap

func ConfigFromMap(m map[string]interface{}) (config *Config, err error)

ConfigFromMap parses and returns config from given map.

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 interface {
	// 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.
	Do(ctx context.Context, command string, args ...interface{}) (result *gvar.Var, err error)

	// Receive receives a single reply as gvar.Var from the Redis server.
	Receive(ctx context.Context) (result *gvar.Var, err error)

	// Close puts the connection back to connection pool.
	Close(ctx context.Context) (err error)
}

Conn is an interface of a connection from universal redis client.

type Message

type Message struct {
	Channel      string
	Pattern      string
	Payload      string
	PayloadSlice []string
}

Message received as result of a PUBLISH command issued by another client.

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, error)

New creates and returns a redis client. It creates a default redis adapter of go-redis.

func NewWithAdapter

func NewWithAdapter(adapter Adapter) *Redis

NewWithAdapter creates and returns a redis client with given adapter.

func (*Redis) Close

func (r *Redis) Close(ctx context.Context) error

Close closes current redis client, closes its connection pool and releases all its related resources.

func (*Redis) Conn

func (r *Redis) Conn(ctx context.Context) (*RedisConn, error)

Conn retrieves and returns a connection object for continuous operations. Note that you should call Close function manually if you do not use this connection any further.

func (*Redis) Do

func (r *Redis) Do(ctx context.Context, command string, args ...interface{}) (*gvar.Var, 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 (*Redis) GetAdapter

func (r *Redis) GetAdapter() Adapter

GetAdapter returns the adapter that is set in current redis client.

func (*Redis) SetAdapter

func (r *Redis) SetAdapter(adapter Adapter)

SetAdapter sets custom adapter for current redis client.

type RedisConn

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

RedisConn is a connection of redis client.

func (*RedisConn) Close

func (c *RedisConn) Close(ctx context.Context) error

Close puts the connection back to connection pool.

func (*RedisConn) Do

func (c *RedisConn) Do(ctx context.Context, command string, args ...interface{}) (reply *gvar.Var, 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 (*RedisConn) Receive

func (c *RedisConn) Receive(ctx context.Context) (*gvar.Var, error)

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

type Subscription

type Subscription struct {
	Kind    string // Can be "subscribe", "unsubscribe", "psubscribe" or "punsubscribe".
	Channel string // Channel name we have subscribed to.
	Count   int    // Number of channels we are currently subscribed to.
}

Subscription received after a successful subscription to channel.

func (*Subscription) String

func (m *Subscription) String() string

String converts current object to a readable string.

Jump to

Keyboard shortcuts

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