Search and commands

↑ ↓ to select · Enter to open · Esc to close

Type to search packages.

redis

v9.24.1
github.com/redis/go-redis/v9

Documentation

pkg.go.dev ↗

Table of contents

↓ to select · Enter to jump· Shift+Enter for source

7921 matches

Top ↑

Package redis implements a Redis client.

Example (customCommand)

{
	Get := func(ctx context.Context, rdb *redis.Client, key string) *redis.StringCmd {
		cmd := redis.NewStringCmd(ctx, "get", key)
		rdb.Process(ctx, cmd)
		return cmd
	}

	v, err := Get(ctx, rdb, "key_does_not_exist").Result()
	fmt.Printf("%q %s", v, err)

}
Output:
"" redis: nil

Example (customCommand2)

{
	v, err := rdb.Do(ctx, "get", "key_does_not_exist").Text()
	fmt.Printf("%q %s", v, err)

}
Output:
"" redis: nil

Example (instrumentation)

{
	rdb := redis.NewClient(&redis.Options{
		Addr:            ":6379",
		DisableIdentity: true,
	})
	rdb.AddHook(redisHook{})

	rdb.Ping(ctx)

}
Output:
starting processing: <[ping]>
dialing tcp :6379
finished dialing tcp :6379
starting processing: <[hello 3]>
finished processing: <[hello 3]>
starting processing: <[client maint_notifications on moving-endpoint-type internal-ip]>
finished processing: <[client maint_notifications on moving-endpoint-type internal-ip]>
finished processing: <[ping]>

Constants

NaN (3 declarations)

const (
	NaN  = internal.NaN  // Not a Number
	Inf  = internal.Inf  // Positive infinity
	NInf = internal.NInf // Negative infinity
)

String representations of special float values. Values are lowercase for consistency with Redis RESP2 protocol responses.

SearchInvalid (14 declarations)

const (
	SearchInvalid = SearchAggregator(iota)
	SearchAvg
	SearchSum
	SearchMin
	SearchMax
	SearchCount
	SearchCountDistinct
	SearchCountDistinctish
	SearchStdDev
	SearchQuantile
	SearchToList
	SearchFirstValue
	SearchRandomSample
	// SearchCollect is the COLLECT reducer for FT.AGGREGATE. Within each
	// GROUPBY group it projects a chosen set of fields from every row and
	// emits them as an array of per-entry maps under the reducer alias.
	// Requires Redis 8.8+ with unstable features enabled
	// (CONFIG SET search-enable-unstable-features yes).
	SearchCollect
)

SearchFieldTypeInvalid (7 declarations)

const (
	SearchFieldTypeInvalid = SearchFieldType(iota)
	SearchFieldTypeNumeric
	SearchFieldTypeTag
	SearchFieldTypeText
	SearchFieldTypeGeo
	SearchFieldTypeVector
	SearchFieldTypeGeoShape
)

SMemberNotFound (5 declarations)

const (
	SMemberNotFound      int64 = -2 // member or key does not exist
	SMemberNoExpiration  int64 = -1 // member exists without an expiration
	SExpireConditionFail int64 = 0  // condition flag not met
	SExpireUpdated       int64 = 1  // expiration set, updated or removed
	SExpireDeleted       int64 = 2  // expiration in the past, member deleted
)

Result codes in the reply of the member expiration commands.

XNackModeSilent (3 declarations)

const (
	XNackModeSilent = "SILENT"
	XNackModeFail   = "FAIL"
	XNackModeFatal  = "FATAL"
)

XNACK modes. See XNackArgs.Mode.

TSReadEarliest (3 declarations)

const (
	TSReadEarliest = "-" // read from the earliest sample
	TSReadLatest   = "+" // latest sample, inclusive
	TSReadNew      = "$" // only samples added after the call
)

TS.READ timestamp cursor sentinels.

Invalid (16 declarations)

const (
	Invalid = Aggregator(iota)
	Avg
	Sum
	Min
	Max
	Range
	Count
	First
	Last
	StdP
	StdS
	VarP
	VarS
	Twa
	CountNaN
	CountAll
)

BitCountIndexBit

const BitCountIndexBit string = "BIT"

BitCountIndexByte

const BitCountIndexByte string = "BYTE"

DefaultPipelineBufferSize

const DefaultPipelineBufferSize = 128 * 1024

DefaultPipelineBufferSize is the per-connection read/write buffer size for the dedicated pipeline pool when no explicit pipeline buffer size is set (the larger of this and the regular buffer size is used). Pipeline connections move whole batches per round trip, so they earn bigger buffers than regular per-command traffic: measured on the autopipeline engine, throughput plateaus around 64 KiB and gains nothing past ~128 KiB for TYPICAL (small-command) traffic, while very large buffers (>=512 KiB) can regress it.

Set to 128 KiB anyway: the extra headroom is not about typical-traffic throughput but about full-duplex's large-payload backpressure guardrail (see MaxBatchBytes's default) — more bufio headroom before a write() to a slow-draining peer blocks widens the margin before that guardrail's cap is reached. The aggregate memory cost stays negligible because the pool this backs holds few connections: the dedicated pipeline pool does not pre-dial by default (DefaultPipelinePoolSize, PipelineMinIdleConns 0), and full-duplex holds one connection per engine plus one idle spare, regardless of pool size.

DefaultPipelinePoolSize

const DefaultPipelinePoolSize = 10

DefaultPipelinePoolSize is the pipeline pool size used when PipelinePoolSize is not set. Pipelining batches many commands per round trip, so it needs far fewer connections than regular traffic. The pool is pure burst capacity: by default it never pre-dials idle connections (it does not inherit MinIdleConns; see PipelineMinIdleConns), so an unused pipeline pool holds no connections at all and the size is only a cap — bursts wider than it spill to the main pool.

DefaultPipelinePoolTimeout

const DefaultPipelinePoolTimeout = 100 * time.Millisecond

DefaultPipelinePoolTimeout caps the dedicated pipeline pool's PoolTimeout. A shorter positive Options.PoolTimeout takes precedence.

Ordinary pipelines and native full-duplex sessions without CSC acquire with TryGet. On saturation, they spill to the main pool without waiting for this timeout; that pool uses its own PoolTimeout.

Native full-duplex sessions on clients with CSC attached use blocking Get and do not spill to the main pool, whose connections may have tracking enabled. This remains true after CSC serving stops. The timeout bounds the wait for a pool turn and a drainer handoff, not dialing or connection initialization. Lease failures follow the existing retry policy, and Close cancels acquisition.

ErrorTypeNil

const ErrorTypeNil = "NIL"

ErrorTypeNil is the error type reported to OTelRecorder.RecordError for a Nil reply.

KeepTTL

const KeepTTL = -1

KeepTTL is a Redis KEEPTTL option to keep existing TTL, it requires your redis-server version >= 6.0, otherwise you will receive an error: (error) ERR syntax error. For example:

rdb.Set(ctx, key, value, redis.KeepTTL)

Nil

const Nil = proto.Nil

Nil reply returned by Redis when key does not exist.

TxFailedErr

const TxFailedErr = proto.RedisError("redis: transaction failed")

TxFailedErr transaction redis failed.

XTrimLimitDisabled

const XTrimLimitDisabled = -1

XTrimLimitDisabled is a sentinel value for the LIMIT argument of stream trimming (XAddArgs.Limit and the XTrim*Approx* commands). Passing it emits an explicit "LIMIT 0", which tells Redis to disable the trimming effort cap entirely. This differs from passing 0, which keeps the historical behavior: no LIMIT clause is sent and Redis applies its implicit default (100 * stream-node-max-entries examined entries).

LIMIT is only valid together with the "~" (approximate) trimming flag; Redis rejects LIMIT used with exact ("=") trimming.

Variables

ErrTemporarilyNotAvailable (6 declarations)

var (
	// ErrTemporarilyNotAvailable is returned when no healthy database can be
	// selected right now; the client keeps attempting failover on subsequent
	// commands. It is also returned when the member a command or batch was routed
	// to was removed mid-flight (a concurrent RemoveDatabase or manual switch): the
	// client is still open and the next attempt lands on the live active, so the
	// caller should retry rather than treat it as terminal.
	ErrTemporarilyNotAvailable = errors.New("redis: multidb: no healthy database available (temporarily)")
	// ErrPermanentlyNotAvailable is returned after MaxFailoverAttempts
	// consecutive failed failover attempts. The client keeps probing members
	// and recovers when one becomes healthy again.
	ErrPermanentlyNotAvailable = errors.New("redis: multidb: no healthy database available (permanently)")
	// ErrInsufficientHealthyDatabases is returned by NewMultiDBClient when the
	// InitialDBState policy is not satisfied. When no enabled member was
	// healthy, that error also matches ErrPermanentlyNotAvailable.
	ErrInsufficientHealthyDatabases = errors.New("redis: multidb: insufficient healthy databases on initialization")
	// ErrTargetUnhealthy is returned by SetActiveDatabase when the requested
	// target database fails its health probe. Use ForceActiveDatabase to switch
	// unconditionally.
	ErrTargetUnhealthy = errors.New("redis: multidb: target database is unhealthy")
	// ErrDatabaseNotFound is returned by the control API when no member has the
	// given id (never added, or already removed). Member ids are stable and
	// never reused, so a removed member's id stays invalid forever.
	ErrDatabaseNotFound = errors.New("redis: multidb: no database with the given id")
	// ErrDatabaseDisabled is returned by SetActiveDatabase when the target's
	// weight is -1 (disabled). Use ForceActiveDatabase to select it anyway.
	ErrDatabaseDisabled = errors.New("redis: multidb: database is disabled (weight -1)")
)

MultiDBClient errors.

EXPERIMENTAL: this API is subject to change, use with caution.

ErrAutoPipelineQueueFull

var ErrAutoPipelineQueueFull = errors.New(
	"redis: autopipeline: queue full (MaxQueuedCommands reached)",
)

ErrAutoPipelineQueueFull is set on a command rejected because the autopipeliner already holds AutoPipelineOptions.MaxQueuedCommands accepted commands. The command was not sent. The caller may retry it later.

EXPERIMENTAL: this API is subject to change, use with caution.

ErrAutoPipelineTimeout

var ErrAutoPipelineTimeout = errors.New(
	"redis: autopipeline: no batch permit within the internal backstop (engine overloaded or a batch is wedged)",
)

ErrAutoPipelineTimeout is set on drained commands when a flush could not obtain a batch permit within the engine's internal backstop — the engine is overloaded or an in-flight batch is wedged (e.g. read timeouts disabled on a dead peer). It is deliberately NOT context.DeadlineExceeded: the caller's own context did not expire, and errors.Is(err, context.DeadlineExceeded) must not fire for an internal engine timeout.

EXPERIMENTAL: this API is subject to change, use with caution.

ErrClosed

var ErrClosed = pool.ErrClosed

ErrClosed performs any operation on the closed client will return this error.

ErrClusterTopologyUnhealthy

var ErrClusterTopologyUnhealthy = errors.New("redis: cluster topology contains a node that is not online")

ErrClusterTopologyUnhealthy indicates that a node required by an operation is reported as unavailable by the cluster topology. Use errors.Is to match this error, which may include details about the node or slot.

ErrCrossSlot

var ErrCrossSlot = proto.RedisError("CROSSSLOT Keys in request don't hash to the same slot")

ErrCrossSlot is returned when keys are used in the same Redis command and the keys are not in the same hash slot. This error is returned by Redis Cluster and will be returned by the client when TxPipeline or TxPipelined is used on a ClusterClient with keys in different slots.

ErrFDPipelineDiverts

var ErrFDPipelineDiverts = errors.New(
	"redis: FDPipelined got a command that must be diverted off the full-duplex pipe")

ErrFDPipelineDiverts is returned when a batch contains a command the engine cannot stream (blocking, per-command read timeout, runs-outside-pipeline, HIMPORT, or one the routing callback rejects). Such a command has to leave the pipe, which would break the batch's contiguity, so the whole call is refused instead of being silently split. A NoRetry command (e.g. RawWriteTo) is refused too: it makes the batch unreplayable as a unit, which the pipe's per-command recovery cannot honor.

ErrFDPipelineSpansEngines

var ErrFDPipelineSpansEngines = errors.New(
	"redis: FDPipelined batch has keys on different full-duplex engines")

ErrFDPipelineSpansEngines is returned when FullDuplexPipes > 1 runs several full-duplex engines (pipes) and the batch's keyed commands hash to different ones. The batch can only ride one wire, and keeping per-first-key order needs each command on its own key's engine, so it is refused rather than split. Pipeline() falls back to an ordinary pipeline for such a batch.

ErrFDPipelineTooLarge

var ErrFDPipelineTooLarge = errors.New(
	"redis: FDPipelined batch is larger than the full-duplex submit queue")

ErrFDPipelineTooLarge is returned when a batch cannot fit the submit queue even when the queue is empty.

ErrFDPipelineUnavailable

var ErrFDPipelineUnavailable = errors.New(
	"redis: FDPipelined requires a full-duplex autopipeliner on a standalone Client")

ErrFDPipelineUnavailable is returned when batch submission is requested on an autopipeliner that has no full-duplex engine. It is deliberately an error rather than a silent fallback to the pooled pipeline path: a caller asking for this wants the commands on the FD wire, and quietly running them somewhere else would be measured (or relied upon) as something it is not.

Batch submission is STANDALONE ONLY. A full-duplex autopipeliner on a ClusterClient reports Config().FullDuplex true but runs one engine per node, and a pipeline can span nodes, so it gets this error and its Pipeline() keeps using the cluster pipeline, as it did before FD batches existed.

ErrHotKeysNoMetrics

var ErrHotKeysNoMetrics = errors.New("redis: at least one metric must be specified for HOTKEYS START")

ErrHotKeysNoMetrics is returned when HotKeysStart is called without any metrics specified.

ErrInvalidCommand

var ErrInvalidCommand = errors.New("invalid command type")

ErrInvalidCommand is returned when an invalid command is passed to ExecuteCommand.

ErrInvalidPool

var ErrInvalidPool = errors.New("invalid pool type")

ErrInvalidPool is returned when the pool type is not supported.

ErrNoScript

var ErrNoScript = proto.RedisError("NOSCRIPT No matching script. Please use EVAL.")

ErrNoScript is returned when EVALSHA is requested for a script digest that is not available in the script cache. Note that this error text is reproduced literally from that used by Redis.

ErrPoolExhausted

var ErrPoolExhausted = pool.ErrPoolExhausted

ErrPoolExhausted is returned from a pool connection method when the maximum number of database connections in the pool has been reached.

ErrPoolTimeout

var ErrPoolTimeout = pool.ErrPoolTimeout

ErrPoolTimeout timed out waiting to get a connection from the connection pool.

ErrRingAutoPipelineUnsupported

var ErrRingAutoPipelineUnsupported = errors.New("redis: AutoPipeline is not supported by Ring")

ErrRingAutoPipelineUnsupported is returned by Ring's AutoPipeline / AsyncAutoPipeline (and their WithOptions forms); check for it with errors.Is. Autopipelining is not implemented for Ring; use the per-shard clients or a ClusterClient. Ring is part of the UniversalClient interface, so these methods exist to satisfy it and fail explicitly rather than being silently absent.

ErrScriptDigestMismatch

var ErrScriptDigestMismatch = errors.New("redis: SCRIPT LOAD returned a digest that does not match the client-computed SHA-1")

ErrScriptDigestMismatch is returned by Script.Load when SCRIPT LOAD answers with a digest that differs from the SHA-1 computed by NewScript. The local digest is kept so EVALSHA stays pinned to this script's source.

ErrSubmitBlockingFace

var ErrSubmitBlockingFace = errors.New(
	"redis: Submit requires the deferred autopipeliner (AsyncAutoPipeline); on the blocking face use the typed methods or Do",
)

ErrSubmitBlockingFace rejects Submit on the blocking face: Submit does not wait, so a windowed caller could have several commands in flight at once — but the blocking face stripes its enqueue queue on the strength of every caller waiting per command, and a non-waiting window there can be reordered. The deferred face (AsyncAutoPipeline) is built for exactly that usage.

EXPERIMENTAL: this API is subject to change, use with caution.

Functions

DialRetryBackoffConstant

func DialRetryBackoffConstant(d time.Duration) func(attempt int) time.Duration

DialRetryBackoffConstant returns a dial retry backoff function that always returns d. attempt is 0-based: attempt=0 is the delay after the 1st failed dial.

DialRetryBackoffExponential

func DialRetryBackoffExponential(minBackoff, maxBackoff time.Duration) func(attempt int) time.Duration

DialRetryBackoffExponential returns a dial retry backoff function that uses exponential backoff with jitter and a cap, using internal.RetryBackoff.

attempt is 0-based: attempt=0 is the delay after the 1st failed dial.

ExtractCommandValue

func ExtractCommandValue(cmd interface{}) (interface{}, error)

ExtractCommandValue extracts the value from a command result using the fast enum-based approach

HasErrorPrefix

func HasErrorPrefix(err error, prefix string) bool

HasErrorPrefix checks if the err is a Redis error and the message contains a prefix.

Showing entries 1–40 of 7661. Use Contents to jump to any section or symbol.

Dependency graph