redis

package
v0.0.0-...-237b7d6 Latest Latest
Warning

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

Go to latest
Published: May 19, 2023 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

app @author LanguageY++2013 2021/8/6 6:24 PM @company soulgame

redis_wrapper @author LanguageY++2013 2022/4/20 5:39 下午 @company soulgame

redis @author LanguageY++2013 2023/5/12 10:11 @company soulgame

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrStreamOutValue = errors.New("stream out must be non-nil pointer to a struct or ptr slice")
	ErrStreamInValue  = errors.New("stream in must be  a struct or struct ptr")
)

Functions

func RegisterRedisWrapperNewFunc

func RegisterRedisWrapperNewFunc(mode ConnectMode, newFunc NewWrapper)

func TestRole

func TestRole(c redis.Conn, expectedRole string) bool

TestRole wraps GetRole in a test to verify if the role matches an expected role string. If there was any error in querying the supplied connection, the function returns false. Works with Redis >= 2.8.12. It's not goroutine safe, but if you call this method on pooled connections then you are OK.

Types

type ByteStreamEntry

type ByteStreamEntry struct {
	ID   string `redis:"-"`
	Data []byte `redis:"data"`
}

type ClusterConfigure

type ClusterConfigure struct {
	Addrs []string `mapstructure:"addrs"` //哨兵地址列表
}

type Configure

type Configure struct {
	Host         string            `mapstructure:"host"`
	Port         int               `mapstructure:"port"`
	Password     string            `mapstructure:"password"`
	MaxIdle      int               `mapstructure:"maxIdle"`
	MaxActive    int               `mapstructure:"maxActive"`
	IdleTimeout  string            `mapstructure:"idleTimeout"` //1s, 1m, 1h
	Prefix       string            `mapstructure:"prefix"`
	ConnectMode  ConnectMode       `mapstructure:"connectMode,string"` //集群模式:sentinel,cluster,proxy
	SentinelInfo SentinelConfigure `mapstructure:"sentinelInfo"`
	ClusterInfo  ClusterConfigure  `mapstructure:"clusterInfo"`
	// contains filtered or unexported fields
}

type ConnectMode

type ConnectMode string

redis 架构模型

const (
	//直连模式
	ConnectModeDirect ConnectMode = "direct"

	// 哨兵模式
	ConnectModeSentinel ConnectMode = "sentinel"

	// cluster模式
	ConnectModeCluster ConnectMode = "cluster"
)

type ConsumerGroup

type ConsumerGroup struct {
	Name            string `redis:"name"`              //消费组名
	Consumers       int    `redis:"consumers"`         //消费组消费者数量
	Pending         int    `redis:"pending"`           //消费组待消费消息数
	LastDeliveredId string `redis:"last-delivered-id"` //最近被传输给消费组的消息ID
	EntriesRead     int    `redis:"entries-read"`      //送给组内消费者的最后一个条目的逻辑 "读取计数器"。
	Lag             int    `redis:"lag"`               //流中仍在等待交付给该组消费者的条目数,如果不能确定该数字,则为NULL。
}

ConsumerGroup stream 消费组信息

type NewWrapper

type NewWrapper func(configure Configure, options ...redis.DialOption) *RedisWrapper

type NoSentinelsAvailable

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

NoSentinelsAvailable is returned when all sentinels in the list are exhausted (or none configured), and contains the last error returned by Dial (which may be nil)

func (NoSentinelsAvailable) Error

func (ns NoSentinelsAvailable) Error() string

type RedisWrapper

type RedisWrapper struct {
	redis.Pool
	Configure Configure
	// contains filtered or unexported fields
}

func NewRedisWrapper

func NewRedisWrapper(configure Configure) *RedisWrapper

func (*RedisWrapper) GetConn

func (rw *RedisWrapper) GetConn() redis.Conn

func (*RedisWrapper) XAck

func (rw *RedisWrapper) XAck(group, queueKey, id string) (acknowledged int, err error)

func (*RedisWrapper) XAdd

func (rw *RedisWrapper) XAdd(key string, in interface{}, params ...interface{}) (err error)

func (*RedisWrapper) XAddWithMaxLen

func (rw *RedisWrapper) XAddWithMaxLen(key string, in interface{}, maxLen int) (err error)

func (*RedisWrapper) XGroupCreate

func (rw *RedisWrapper) XGroupCreate(key, groupName, initId string) (reply string, err error)

XGroupCreate 创建消费组

返回值:
	reply: 成功返回OK

func (*RedisWrapper) XGroupCreateFromBeginning

func (rw *RedisWrapper) XGroupCreateFromBeginning(key, groupName string) (reply string, err error)

func (*RedisWrapper) XGroupCreateFromTail

func (rw *RedisWrapper) XGroupCreateFromTail(key, groupName string) (reply string, err error)

func (*RedisWrapper) XGroupDestroy

func (rw *RedisWrapper) XGroupDestroy(key, groupName string) (reply string, err error)

func (*RedisWrapper) XInfoGroups

func (rw *RedisWrapper) XInfoGroups(queueKey string) (ret []*ConsumerGroup, err error)

XInfoGroups 返回queueKey关联的消费组列表信息

func (*RedisWrapper) XInfoStream

func (rw *RedisWrapper) XInfoStream(queueKey string) (ret *StreamInfo, err error)

XInfoStream 返回存储在queueKey的流基本信息

func (*RedisWrapper) XLen

func (rw *RedisWrapper) XLen(key string) (ret int, err error)

func (*RedisWrapper) XRead

func (rw *RedisWrapper) XRead(key string, count int, timeout time.Duration, out interface{}) (err error)

func (*RedisWrapper) XReadGroup

func (rw *RedisWrapper) XReadGroup(group, consumer string, count int, timeout time.Duration, queueKey string, out interface{}) (err error)

type Sentinel

type Sentinel struct {
	// Addrs is a slice with known Sentinel addresses.
	Addrs []string

	// MasterName is a name of Redis master Sentinel servers monitor.
	MasterName string

	// Dial is a user supplied function to connect to Sentinel on given address. This
	// address will be chosen from Addrs slice.
	// Note that as per the redis-sentinel client guidelines, a timeout is mandatory
	// while connecting to Sentinels, and should not be set to 0.
	Dial func(addr string) (redis.Conn, error)

	// Pool is a user supplied function returning custom connection pool to Sentinel.
	// This can be useful to tune options if you are not satisfied with what default
	// Sentinel pool offers. See defaultPool() method for default pool implementation.
	// In most cases you only need to provide Dial function and let this be nil.
	Pool func(addr string) *redis.Pool
	// contains filtered or unexported fields
}

Sentinel provides a way to add high availability (HA) to Redis Pool using preconfigured addresses of Sentinel servers and name of master which Sentinels monitor. It works with Redis >= 2.8.12 (mostly because of ROLE command that was introduced in that version, it's possible though to support old versions using INFO command).

Example of the simplest usage to contact master "mymaster":

func newSentinelPool() *redis.Pool {
	sntnl := &sentinel.Sentinel{
		Addrs:      []string{":26379", ":26380", ":26381"},
		MasterName: "mymaster",
		Dial: func(addr string) (redis.Conn, error) {
			timeout := 500 * time.Millisecond
			c, err := redis.DialTimeout("tcp", addr, timeout, timeout, timeout)
			if err != nil {
				return nil, err
			}
			return c, nil
		},
	}
	return &redis.Pool{
		MaxIdle:     3,
		MaxActive:   64,
		Wait:        true,
		IdleTimeout: 240 * time.Second,
		Dial: func() (redis.Conn, error) {
			masterAddr, err := sntnl.MasterAddr()
			if err != nil {
				return nil, err
			}
			c, err := redis.Dial("tcp", masterAddr)
			if err != nil {
				return nil, err
			}
			return c, nil
		},
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			if !sentinel.TestRole(c, "master") {
				return errors.New("Role check failed")
			} else {
				return nil
			}
		},
	}
}

func (*Sentinel) Close

func (s *Sentinel) Close() error

Close closes current connection to Sentinel.

func (*Sentinel) Discover

func (s *Sentinel) Discover() error

Discover allows to update list of known Sentinel addresses. From docs:

A client may update its internal list of Sentinel nodes following this procedure: 1) Obtain a list of other Sentinels for this master using the command SENTINEL sentinels <master-name>. 2) Add every ip:port pair not already existing in our list at the end of the list.

func (*Sentinel) MasterAddr

func (s *Sentinel) MasterAddr() (string, error)

MasterAddr returns an address of current Redis master instance.

func (*Sentinel) SentinelAddrs

func (s *Sentinel) SentinelAddrs() ([]string, error)

SentinelAddrs returns a slice of known Sentinel addresses Sentinel server aware of.

func (*Sentinel) SlaveAddrs

func (s *Sentinel) SlaveAddrs() ([]string, error)

SlaveAddrs returns a slice with known slave addresses of current master instance.

func (*Sentinel) Slaves

func (s *Sentinel) Slaves() ([]*Slave, error)

Slaves returns a slice with known slaves of master instance.

type SentinelConfigure

type SentinelConfigure struct {
	Addrs      string `mapstructure:"addrs"`      //哨兵地址列表
	MasterName string `mapstructure:"masterName"` //master节点名 sentinel monitor mymaster 127.0.0.1 6379 2
}

格式:https://pkg.go.dev/github.com/mitchellh/mapstructure

type Slave

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

Slave represents a Redis slave instance which is known by Sentinel.

func (*Slave) Addr

func (s *Slave) Addr() string

Addr returns an address of slave.

func (*Slave) Available

func (s *Slave) Available() bool

Available returns if slave is in working state at moment based on information in slave flags.

type StreamBaseMsg

type StreamBaseMsg struct {
	ID string `redis:"-"`
}

type StreamEntry

type StreamEntry struct {
	ID     string `redis:"-"`
	Fields map[string]string
}

StreamEntry stream 条目

type StreamInfo

type StreamInfo struct {
	Length            int         `redis:"length"`               //流中的条目数
	RadixTreeKeys     int         `redis:"radix-tree-keys"`      //底层radix数据结构中的键的数量
	RadixTreeNodes    int         `redis:"radix-tree-nodes"`     //底层radix数据结构中的节点数
	Groups            int         `redis:"groups"`               //为该流定义的消费者组的数量
	LastGeneratedId   string      `redis:"last-generated-id"`    //被添加到流中的最近的条目的ID
	MaxDeletedEntryId string      `redis:"max-deleted-entry-id"` //从流中被删除的最大条目ID
	EntriesAdded      int         `redis:"entries-added"`        //在流的生命周期内添加到流中的所有条目的计数
	FirstEntry        StreamEntry `redis:"-"`                    //流中第一个条目的ID和字段值图示
	LastEntry         StreamEntry `redis:"-"`                    //流中最后一个条目的ID和字段值图示
}

Jump to

Keyboard shortcuts

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