redigo

package module
v1.2.4 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 14 Imported by: 1 module, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

redigo

redis go client

  • 支持哨兵模式(英文逗号或分号分隔多个哨兵地址)
  • 支持集群模式(英文逗号或分号分隔多个节点地址)
  • 支持struct或slice对象json自动序列化/反序列化
  • 支持基本类型直接赋值/取值

exmaples

package redigo

import (
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
)

const (
	expireSeconds = 60 * time.Second
	redisAddress  = "127.0.0.1:6379,127.0.0.1:6380"
	redisPassword = "123456"
)
const (
	redigoNotFoundKey = "redigoNotFoundKey"
	redigoSetJsonKey  = "redigoSetJsonKey"
	redigoSetIntKey   = "redigoSetIntKey"
	redigoDelKey      = "redigoDelTestKey"
	redigoListKey     = "redigoListKey"
)

type User struct {
	ID   int32
	Name string
}

var opts = []Option{
	WithAddress(redisAddress),
	WithPassword(redisPassword),
}

func TestRedigo_Set(t *testing.T) {
	users := []*User{
		{
			ID:   10086,
			Name: "dianxin",
		},
		{
			ID:   10010,
			Name: "liantong",
		},
	}
	rediscli := NewClient(opts...)
	var id string
	ok, err := rediscli.Get(redigoNotFoundKey, &id)
	if err != nil {
		t.Fatal(err)
	}
	if !ok {
		t.Logf("key [%s] not found", redigoNotFoundKey)
	}

	err = rediscli.Set(redigoSetJsonKey, &users, WithEX(expireSeconds), WithNX())
	if err != nil {
		t.Fatal(err)
	}
	t.Logf("Set key [%s] ok", redigoSetJsonKey)

	var users2 []User
	ok, err = rediscli.Get(redigoSetJsonKey, &users2)
	if err != nil {
		t.Fatal(err)
	}
	if !ok {
		t.Fatalf("key [%s] not found", redigoSetJsonKey)
	}
	t.Logf("GET key [%v] value %+v", redigoSetJsonKey, users2)

	var ttl int64
	ttl, err = rediscli.TTL(redigoSetJsonKey)
	if err != nil {
		t.Fatal(err)
	}
	t.Logf("TTL key [%s] return [%v]", redigoSetJsonKey, ttl)

	err = rediscli.Set(redigoSetIntKey, uint64(592609353484206164), WithEX(expireSeconds))
	if err != nil {
		t.Fatal(err)
	}

	ok, err = rediscli.Get(redigoSetIntKey, &id)
	if err != nil {
		t.Fatal(err)
	}
	if !ok {
		t.Fatalf("key [%s] not found", redigoSetIntKey)
	}
	t.Logf("GET key [%v] value [%+v]", redigoSetIntKey, id)
}

func TestRedigo_Del(t *testing.T) {
	// First, set a key to ensure it exists
	rediscli := NewClient(opts...)
	testValue := "test_value_for_deletion"
	err := rediscli.Set(redigoDelKey, testValue, WithEX(expireSeconds))
	if err != nil {
		t.Fatal(err)
	}

	var ttl int64
	ttl, err = rediscli.TTL(redigoDelKey)
	if err != nil {
		t.Fatal(err)
	}
	t.Logf("key %s TTL %v", redigoDelKey, ttl)
	// Now delete the key
	var ret int64
	ret, err = rediscli.Del(redigoDelKey)
	if err != nil {
		t.Fatal(err)
	}
	t.Logf("delete return %v", ret)

	// Verify the key is deleted by trying to get it
	var ok bool
	var v string
	ok, err = rediscli.Get(redigoDelKey, &v)
	if err != nil {
		t.Fatal("got error when getting deleted key")
	}
	if !ok {
		t.Logf("DEL key [%v] successful", redigoDelKey)
	} else {
		t.Fatalf("DEL key [%s] found, not expected", redigoDelKey)
	}
}

func TestRedigo_List(t *testing.T) {
	var err error
	rediscli := NewClient(opts...)
	_, err = rediscli.ListPush(redigoListKey, []string{"1", "3", "5", "7"})
	if err != nil {
		t.Fatal(err)
	}

	var list []string
	err = rediscli.ListRange(redigoListKey, 0, -1, &list)
	if err != nil {
		t.Fatal(err)
	}
	var n int64
	n, err = rediscli.ListLen(redigoListKey)
	if err != nil {
		t.Fatal(err)
	}
	t.Logf("list count %v range %+v", n, list)

	list = []string{}
	err = rediscli.ListPop(redigoListKey, 1, &list, WithRright())
	if err != nil {
		t.Fatal(err)
	}
	t.Logf("list pop %+v", list)
}

func TestUnwind(t *testing.T) {
	// 测试普通值
	assert.Equal(t, []any{42}, unwind(42))
	assert.Equal(t, []any{"hello"}, unwind("hello"))
	assert.Equal(t, []any{3.14}, unwind(3.14))

	// 测试nil
	assert.Equal(t, []any{}, unwind(nil))

	// 测试切片
	assert.Equal(t, []any{1, 2, 3}, unwind([]int{1, 2, 3}))
	assert.Equal(t, []any{"a", "b", "c"}, unwind([]string{"a", "b", "c"}))

	// 测试空切片
	assert.Equal(t, []any{}, unwind([]int{}))
	assert.Equal(t, []any{}, unwind([]string{}))

	// 测试数组
	assert.Equal(t, []any{1, 2, 3}, unwind([3]int{1, 2, 3}))

	// 测试混合类型切片
	mixed := []any{1, "hello", 3.14, true}
	assert.Equal(t, mixed, unwind(mixed))
}


Documentation

Index

Constants

View Source
const (
	RedisOK = "OK"
)

Variables

View Source
var (
	ErrKeyExists             = errors.New("key already exists")
	ErrKeyNotExists          = errors.New("key does not exist")
	ErrInvalidResponse       = errors.New("invalid response from server")
	ErrLockAcquisitionFailed = errors.New("failed to acquire lock")
	ErrLockNotHeld           = errors.New("lock not held by this instance")
)

Functions

This section is empty.

Types

type Client added in v1.0.1

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

func NewClient added in v1.0.0

func NewClient(opts ...Option) *Client

func (*Client) BlockLock added in v1.0.1

func (r *Client) BlockLock(key string, expiry time.Duration) (func() error, error)

BlockLock acquires a distributed lock in blocking mode It returns an unlock function and an error if failed to acquire lock

func (*Client) Decr added in v1.0.1

func (r *Client) Decr(key string, v ...int64) (ret int64, err error)

func (*Client) Del added in v1.0.1

func (r *Client) Del(key string) (int64, error)

func (*Client) Do added in v1.0.1

func (r *Client) Do(cmd string, args ...any) (any, error)

func (*Client) Exists added in v1.0.1

func (r *Client) Exists(key string) (bool, error)

func (*Client) Expire added in v1.0.1

func (r *Client) Expire(key string, expiration time.Duration) error

func (*Client) Get added in v1.0.1

func (r *Client) Get(key string, v any) (ok bool, err error)

func (*Client) Incr added in v1.0.1

func (r *Client) Incr(key string, v any) (ret int64, err error)

Incr increment the value of a key by 1 if v is nil, otherwise v must be an integer or float number

func (*Client) IsSentinel added in v1.2.0

func (r *Client) IsSentinel() bool

func (*Client) ListLen added in v1.0.1

func (r *Client) ListLen(key string) (n int64, err error)

func (*Client) ListPop added in v1.0.1

func (r *Client) ListPop(key string, n int, v any, opts ...ListOption) (err error)

阻塞模式(BRPOP/BLPOP) n表示超时时间(s), 否则n表示取值个数

func (*Client) ListPush added in v1.0.1

func (r *Client) ListPush(key string, v any, opts ...ListOption) (ret int64, err error)

func (*Client) ListRange added in v1.0.1

func (r *Client) ListRange(key string, start, stop int64, v any) (err error)

func (*Client) Set added in v1.0.1

func (r *Client) Set(key string, v any, opts ...SetOption) error

func (*Client) TTL added in v1.0.1

func (r *Client) TTL(key string) (int64, error)

func (*Client) TryLock added in v1.0.1

func (r *Client) TryLock(key string, expiry time.Duration, timeout time.Duration) (func() error, error)

TryLock tries to acquire a distributed lock with a timeout It returns an unlock function and an error if failed to acquire lock within timeout

type ListOption

type ListOption func(*listOptions)

func WithBlock

func WithBlock() ListOption

func WithRright

func WithRright() ListOption

type Lock

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

Lock represents a distributed lock

type Option

type Option func(*redigoOptions)

func WithAddress

func WithAddress(address string) Option

func WithClientName

func WithClientName(clientName string) Option

func WithConnTimeout

func WithConnTimeout(connTimeout time.Duration) Option

func WithDB

func WithDB(db int) Option

func WithIdleTimeout

func WithIdleTimeout(idleTimeout time.Duration) Option

func WithMaxActive

func WithMaxActive(maxActive int) Option

func WithMaxConnLifetime

func WithMaxConnLifetime(maxConnLifetime time.Duration) Option

func WithMaxIdle

func WithMaxIdle(maxIdle int) Option

func WithPassword

func WithPassword(password string) Option

func WithSentinel added in v1.1.0

func WithSentinel(sentinel *SentinelConfig) Option

func WithSkipVerify

func WithSkipVerify(skipVerify bool) Option

func WithTLSConfig

func WithTLSConfig(tlsConfig *tls.Config) Option

func WithUseTLS

func WithUseTLS(useTLS bool) Option

func WithWait

func WithWait(wait bool) Option

type SentinelConfig added in v1.1.0

type SentinelConfig struct {
	MasterName       string
	SentinelPassword string
}

type SetOption

type SetOption func(*setOptions)

func WithEX

func WithEX(expiry time.Duration) SetOption

WithEX set EX option

func WithEXRand added in v0.2.1

func WithEXRand(expiry time.Duration, randN int) SetOption

func WithNX

func WithNX() SetOption

WithNX set NX option

func WithPX

func WithPX(px int64) SetOption

WithPX set PX option

func WithXX

func WithXX() SetOption

WithXX set XX option

Jump to

Keyboard shortcuts

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