### Install valkeylimiter module Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeylimiter Command to install the package via go get. ```bash go get github.com/valkey-io/valkey-go/valkeylimiter ``` -------------------------------- ### Initialize and use RateLimiter Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeylimiter Full example demonstrating initialization, checking, and allowing requests with the rate limiter. ```go package main import ( "context" "fmt" "time" "github.com/valkey-io/valkey-go" "github.com/valkey-io/valkey-go/valkeylimiter" ) func main() { // Initialize a new rate limiter with a limit of 5 requests per minute limiter, err := valkeylimiter.NewRateLimiter(valkeylimiter.RateLimiterOption{ ClientOption: valkey.ClientOption{InitAddress: []string{"localhost:6379"}}, KeyPrefix: "api_rate_limit", Limit: 5, Window: time.Minute, }) if err != nil { panic(err) } identifier := "user_123" // Check if a request is allowed result, err := limiter.Check(context.Background(), identifier) if err != nil { panic(err) } fmt.Printf("Allowed: %v, Remaining: %d, RetryAfter: %v\n", result.Allowed, result.Remaining, result.RetryAfter) // Allow a request result, err = limiter.Allow(context.Background(), identifier) if err != nil { panic(err) } fmt.Printf("Allowed: %v, Remaining: %d, RetryAfter: %v\n", result.Allowed, result.Remaining, result.RetryAfter) // Allow multiple requests result, err = limiter.AllowN(context.Background(), identifier, 3) if err != nil { panic(err) } fmt.Printf("Allowed: %v, Remaining: %d, RetryAfter: %v\n", result.Allowed, result.Remaining, result.RetryAfter) } ``` -------------------------------- ### Implement Cache-Aside with valkeyaside Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeyaside Demonstrates initializing a client and using the Get method to fetch data from a database with a cache-aside strategy. ```go package main import ( "context" "database/sql" "time" "github.com/valkey-io/valkey-go" "github.com/valkey-io/valkey-go/valkeyaside" ) func main() { var db sql.DB client, err := valkeyaside.NewClient(valkeyaside.ClientOption{ ClientOption: valkey.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}, }) if err != nil { panic(err) } val, err := client.Get(context.Background(), time.Minute, "mykey", func(ctx context.Context, key string) (val string, err error) { if err = db.QueryRowContext(ctx, "SELECT val FROM mytab WHERE id = ?", key).Scan(&val); err == sql.ErrNoRows { val = "_nil_" // cache nil to avoid penetration. err = nil // clear err in the case of sql.ErrNoRows. } return }) if err != nil { panic(err) } else if val == "_nil_" { val = "" err = sql.ErrNoRows } else { // ... } } ``` -------------------------------- ### Initialize and use valkeycompatmock adapter Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompatmock Demonstrates setting up a gomock controller and defining expectations for Get and Set operations. ```go package main import ( "context" "testing" "github.com/valkey-io/valkey-go/mock" "github.com/valkey-io/valkey-go/valkeycompat" "github.com/valkey-io/valkey-go/valkeycompatmock" "go.uber.org/mock/gomock" ) func TestExample(t *testing.T) { ctrl := gomock.NewController(t) m := mock.NewClient(ctrl) compatmock := valkeycompatmock.NewAdapter(m) compatmock.ExpectSet("key", "val", 0).SetVal("OK") compatmock.ExpectGet("key").SetVal("val") rdb := valkeycompat.NewAdapter(m) rdb.Set(context.Background(), "key", "val", 0) rdb.Get(context.Background(), "key") } ``` -------------------------------- ### Connect Go Client via RDMA Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeyrdma Example of initializing a Valkey client with the RDMA dialer function. ```go package main import ( "context" "github.com/valkey-io/valkey-go" "github.com/valkey-io/valkey-go/valkeyrdma" ) func main() { client, err := valkey.NewClient(valkey.ClientOption{ InitAddress: []string{":6378"}, DialCtxFn: valkeyrdma.DialCtxFn, }) ... } ``` -------------------------------- ### Build Valkey with RDMA Support Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeyrdma Commands to install dependencies and compile the Valkey server with the RDMA module. ```bash sudo apt install -y build-essential pkg-config libjemalloc-dev sudo apt install -y librdmacm-dev rdma-core rdmacm-utils wget https://github.com/valkey-io/valkey/archive/refs/tags/9.0.1.tar.gz tar -zxvf 9.0.1.tar.gz && rm 9.0.1.tar.gz cd valkey-9.0.1 BUILD_RDMA=module make ``` -------------------------------- ### Configure RDMA Network and Server Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeyrdma Commands to set up the RoCEv2 link, verify connectivity with rping, and start the Valkey server with RDMA. ```bash sudo rdma link add rxe0 type rxe netdev ``` ```bash rping -s -a -v ``` ```bash rping -c -a -v ``` ```bash ./src/valkey-server --loadmodule ./src/valkey-rdma.so --rdma-bind --rdma-port 6378 ``` ```bash ./src/valkey-cli -h -p 6378 --rdma hello 3 ``` -------------------------------- ### Common command response parsing examples Source: https://pkg.go.dev/github.com/valkey-io/valkey-go A reference for selecting the correct parser method based on the expected Valkey command response type. ```go // GET client.Do(ctx, client.B().Get().Key("k").Build()).ToString() client.Do(ctx, client.B().Get().Key("k").Build()).AsInt64() // MGET client.Do(ctx, client.B().Mget().Key("k1", "k2").Build()).ToArray() // SET client.Do(ctx, client.B().Set().Key("k").Value("v").Build()).Error() // INCR client.Do(ctx, client.B().Incr().Key("k").Build()).AsInt64() // HGET client.Do(ctx, client.B().Hget().Key("k").Field("f").Build()).ToString() // HMGET client.Do(ctx, client.B().Hmget().Key("h").Field("a", "b").Build()).ToArray() // HGETALL client.Do(ctx, client.B().Hgetall().Key("h").Build()).AsStrMap() // EXPIRE client.Do(ctx, client.B().Expire().Key("k").Seconds(1).Build()).AsInt64() // HEXPIRE client.Do(ctx, client.B().Hexpire().Key("h").Seconds(1).Fields().Numfields(2).Field("f1", "f2").Build()).AsIntSlice() // ZRANGE client.Do(ctx, client.B().Zrange().Key("k").Min("1").Max("2").Build()).AsStrSlice() // ZRANK client.Do(ctx, client.B().Zrank().Key("k").Member("m").Build()).AsInt64() // ZSCORE client.Do(ctx, client.B().Zscore().Key("k").Member("m").Build()).AsFloat64() // ZRANGE client.Do(ctx, client.B().Zrange().Key("k").Min("0").Max("-1").Build()).AsStrSlice() client.Do(ctx, client.B().Zrange().Key("k").Min("0").Max("-1").Withscores().Build()).AsZScores() // ZPOPMIN client.Do(ctx, client.B().Zpopmin().Key("k").Build()).AsZScore() client.Do(ctx, client.B().Zpopmin().Key("myzset").Count(2).Build()).AsZScores() // SCARD client.Do(ctx, client.B().Scard().Key("k").Build()).AsInt64() // SMEMBERS client.Do(ctx, client.B().Smembers().Key("k").Build()).AsStrSlice() // LINDEX client.Do(ctx, client.B().Lindex().Key("k").Index(0).Build()).ToString() // LPOP client.Do(ctx, client.B().Lpop().Key("k").Build()).ToString() client.Do(ctx, client.B().Lpop().Key("k").Count(2).Build()).AsStrSlice() // SCAN client.Do(ctx, client.B().Scan().Cursor(0).Build()).AsScanEntry() // FT.SEARCH client.Do(ctx, client.B().FtSearch().Index("idx").Query("@f:v").Build()).AsFtSearch() // GEOSEARCH client.Do(ctx, client.B().Geosearch().Key("k").Fromlonlat(1, 1).Bybox(1).Height(1).Km().Build()).AsGeosearch() ``` -------------------------------- ### String Command Methods Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Methods for performing standard string operations like Get, Set, and increment/decrement. ```go SortStore(ctx context.Context, key, store string, sort Sort) *IntCmd SortInterfaces(ctx context.Context, key string, sort Sort) *SliceCmd Touch(ctx context.Context, keys ...string) *IntCmd TTL(ctx context.Context, key string) *DurationCmd Type(ctx context.Context, key string) *StatusCmd Append(ctx context.Context, key, value string) *IntCmd Decr(ctx context.Context, key string) *IntCmd DecrBy(ctx context.Context, key string, decrement int64) *IntCmd Get(ctx context.Context, key string) *StringCmd GetRange(ctx context.Context, key string, start, end int64) *StringCmd GetSet(ctx context.Context, key string, value any) *StringCmd GetEx(ctx context.Context, key string, expiration time.Duration) *StringCmd GetDel(ctx context.Context, key string) *StringCmd Incr(ctx context.Context, key string) *IntCmd IncrBy(ctx context.Context, key string, value int64) *IntCmd IncrByFloat(ctx context.Context, key string, value float64) *FloatCmd MGet(ctx context.Context, keys ...string) *SliceCmd MSet(ctx context.Context, values ...any) *StatusCmd MSetNX(ctx context.Context, values ...any) *BoolCmd Set(ctx context.Context, key string, value any, expiration time.Duration) *StatusCmd SetArgs(ctx context.Context, key string, value any, a SetArgs) *StatusCmd SetEX(ctx context.Context, key string, value any, expiration time.Duration) *StatusCmd SetNX(ctx context.Context, key string, value any, expiration time.Duration) *BoolCmd SetXX(ctx context.Context, key string, value any, expiration time.Duration) *BoolCmd SetRange(ctx context.Context, key string, offset int64, value string) *IntCmd StrLen(ctx context.Context, key string) *IntCmd Copy(ctx context.Context, sourceKey string, destKey string, db int64, replace bool) *IntCmd ``` -------------------------------- ### Initialize and Execute Commands with Valkey Source: https://pkg.go.dev/github.com/valkey-io/valkey-go Demonstrates basic client initialization and command execution using the builder pattern. Ensure the client is closed after use to release resources. ```go package main import ( "context" "github.com/valkey-io/valkey-go" ) func main() { client, err := valkey.NewClient(valkey.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}) if err != nil { panic(err) } defer client.Close() ctx := context.Background() // SET key val NX err = client.Do(ctx, client.B().Set().Key("key").Value("val").Nx().Build()).Error() // HGETALL hm hm, err := client.Do(ctx, client.B().Hgetall().Key("hm").Build()).AsStrMap() } ``` -------------------------------- ### HLen Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Gets the number of fields in a hash. ```go func (c *Compat) HLen(ctx context.Context, key string) *IntCmd ``` -------------------------------- ### HGetDel Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Gets and deletes fields from a hash. ```go func (c *Compat) HGetDel(ctx context.Context, key string, fields ...string) *StringSliceCmd ``` -------------------------------- ### JSONGetArgs Structure Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Arguments for JSON get operations. ```go type JSONGetArgs struct { Indent string Newline string Space string } ``` -------------------------------- ### TSGet Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Gets the last sample of a time-series key. ```APIDOC ## func (*Compat) TSGet ### Description Gets the last sample of a time-series key. ### Signature `func (c *Compat) TSGet(ctx context.Context, key string) *TSTimestampValueCmd` ``` -------------------------------- ### HPTTL Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Gets the time-to-live for hash fields in milliseconds. ```go func (c *Compat) HPTTL(ctx context.Context, key string, fields ...string) *IntSliceCmd ``` -------------------------------- ### Initialize Valkey Client with OpenTelemetry Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeyotel Demonstrates creating a client with OpenTelemetry enabled and using the Labeler to add custom attributes to cache metrics. ```go package main import ( "context" "time" "github.com/valkey-io/valkey-go" "github.com/valkey-io/valkey-go/valkeyotel" "go.opentelemetry.io/otel/attribute" ) func main() { client, err := valkeyotel.NewClient(valkey.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}) if err != nil { panic(err) } defer client.Close() // Basic usage ctx := context.Background() client.DoCache(ctx, client.B().Get().Key("mykey").Cache(), time.Minute) // Add custom labels to cache metrics using Labeler // Check if labeler exists in context, create new context only if needed bookLabeler, ok := valkeyotel.LabelerFromContext(ctx) if !ok { ctx = valkeyotel.ContextWithLabeler(ctx, bookLabeler) } bookLabeler.Add(attribute.String("key_pattern", "book")) client.DoCache(ctx, client.B().Get().Key("book:123").Cache(), time.Minute) // Track with multiple attributes authorLabeler, ok := valkeyotel.LabelerFromContext(ctx) if !ok { ctx = valkeyotel.ContextWithLabeler(ctx, authorLabeler) } authorLabeler.Add( attribute.String("key_pattern", "author"), attribute.String("tenant", "acme"), ) client.DoCache(ctx, client.B().Get().Key("author:456").Cache(), time.Minute) } ``` -------------------------------- ### HGetEX Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Gets fields from a hash and sets their expiration. ```go func (c *Compat) HGetEX(ctx context.Context, key string, fields ...string) *StringSliceCmd ``` -------------------------------- ### Initialize New Client Source: https://pkg.go.dev/github.com/valkey-io/valkey-go NewClient initializes a client for either cluster or standalone mode based on the provided ClientOption. ```go func NewClient(option ClientOption) (client Client, err error) ``` -------------------------------- ### Initialize OM Repository Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/om Demonstrates defining a struct with Valkey tags and initializing a repository using NewHashRepository. ```go package main import ( "context" "fmt" "time" "github.com/valkey-io/valkey-go" "github.com/valkey-io/valkey-go/om" ) type Example struct { Key string `json:"key" valkey:",key"` // the valkey:",key" is required to indicate which field is the ULID key Ver int64 `json:"ver" valkey:",ver"` // the valkey:",ver" is optional for optimistic locking to prevent lost update ExAt time.Time `json:"exat" valkey:",exat"` // the valkey:",exat" is optional for setting record expiry with unix timestamp Str string `json:"str"` // both NewHashRepository and NewJSONRepository use json tag as field name } func main() { ctx := context.Background() c, err := valkey.NewClient(valkey.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}) if err != nil { panic(err) } // create the repo with NewHashRepository or NewJSONRepository repo := om.NewHashRepository("my_prefix", Example{}, c) exp := repo.NewEntity() exp.Str = "mystr" exp.ExAt = time.Now().Add(time.Hour) fmt.Println(exp.Key) // output 01FNH4FCXV9JTB9WTVFAAKGSYB repo.Save(ctx, exp) // success // lookup "my_prefix:01FNH4FCXV9JTB9WTVFAAKGSYB" through client side caching exp2, _ := repo.FetchCache(ctx, exp.Key, time.Second*5) fmt.Println(exp2.Str) // output "mystr", which is equal to exp.Str exp2.Ver = 0 // if someone changes the version during your GET then SET operation, repo.Save(ctx, exp2) // the save will fail with ErrVersionMismatch. } ``` -------------------------------- ### HExpireTime Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Gets the expiration time of hash fields. ```go func (c *Compat) HExpireTime(ctx context.Context, key string, fields ...string) *IntSliceCmd ``` -------------------------------- ### ZRandMember Operations Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Gets random members from a sorted set. ```go func (c *Pipeline) ZRandMember(ctx context.Context, key string, count int64) *StringSliceCmd ``` ```go func (c *Pipeline) ZRandMemberWithScores(ctx context.Context, key string, count int64) *ZSliceCmd ``` -------------------------------- ### Create Index Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Initializes a new index with specified options and schema. ```go func (c *Compat) FTCreate(ctx context.Context, index string, options *FTCreateOptions, schema ...*FieldSchema) *StatusCmd ``` -------------------------------- ### ZMScore Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Gets the scores of multiple members in a sorted set. ```go func (c *Pipeline) ZMScore(ctx context.Context, key string, members ...string) *FloatSliceCmd ``` -------------------------------- ### Initialize and use a Bloom Filter Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeyprob Demonstrates creating a Bloom filter, adding elements, and checking for their existence. ```go package main import ( "context" "fmt" "github.com/valkey-io/valkey-go" "github.com/valkey-io/valkey-go/valkeyprob" ) func main() { client, err := valkey.NewClient(valkey.ClientOption{ InitAddress: []string{"localhost:6379"}, }) if err != nil { panic(err) } bf, err := valkeyprob.NewBloomFilter(client, "bloom_filter", 1000, 0.01) err = bf.Add(context.Background(), "hello") if err != nil { panic(err) } err = bf.Add(context.Background(), "world") if err != nil { panic(err) } exists, err := bf.Exists(context.Background(), "hello") if err != nil { panic(err) } fmt.Println(exists) // true exists, err = bf.Exists(context.Background(), "world") if err != nil { panic(err) } fmt.Println(exists) // true } ``` -------------------------------- ### HPExpireTime Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Gets the expiration time of hash fields in milliseconds. ```go func (c *Compat) HPExpireTime(ctx context.Context, key string, fields ...string) *IntSliceCmd ``` -------------------------------- ### Configuration Methods Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Methods for managing Valkey server configuration. ```go func (c *Compat) ConfigGet(ctx context.Context, parameter string) *StringStringMapCmd ``` ```go func (c *Compat) ConfigResetStat(ctx context.Context) *StatusCmd ``` ```go func (c *Compat) ConfigRewrite(ctx context.Context) *StatusCmd ``` ```go func (c *Compat) ConfigSet(ctx context.Context, parameter, value string) *StatusCmd ``` -------------------------------- ### HGetEXWithArgs Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Gets fields from a hash and sets their expiration with options. ```go func (c *Compat) HGetEXWithArgs(ctx context.Context, key string, options *HGetEXOptions, fields ...string) *StringSliceCmd ``` -------------------------------- ### Get Configuration Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Retrieves a RediSearch configuration parameter value. ```go func (c *Compat) FTConfigGet(ctx context.Context, option string) *MapMapStringInterfaceCmd ``` -------------------------------- ### Command and Configuration Pipeline Methods Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Methods for retrieving command information and managing server configuration. ```go func (c *Pipeline) Command(ctx context.Context) *CommandsInfoCmd ``` ```go func (c *Pipeline) CommandGetKeys(ctx context.Context, commands ...any) *StringSliceCmd ``` ```go func (c *Pipeline) CommandGetKeysAndFlags(ctx context.Context, commands ...any) *KeyFlagsCmd ``` ```go func (c *Pipeline) CommandList(ctx context.Context, filter FilterBy) *StringSliceCmd ``` ```go func (c *Pipeline) ConfigGet(ctx context.Context, parameter string) *StringStringMapCmd ``` ```go func (c *Pipeline) ConfigResetStat(ctx context.Context) *StatusCmd ``` ```go func (c *Pipeline) ConfigRewrite(ctx context.Context) *StatusCmd ``` ```go func (c *Pipeline) ConfigSet(ctx context.Context, parameter, value string) *StatusCmd ``` -------------------------------- ### Instantiate Valkey Client Source: https://pkg.go.dev/github.com/valkey-io/valkey-go Create a new client instance using various connection options such as standalone, cluster, sentinel, or unix sockets. ```go // Connect to a single valkey node: client, err := valkey.NewClient(valkey.ClientOption{ InitAddress: []string{"127.0.0.1:6379"}, }) // Connect to a standalone valkey with replicas client, err := valkey.NewClient(valkey.ClientOption{ InitAddress: []string{"127.0.0.1:6379"}, Standalone: valkey.StandaloneOption{ // Note that these addresses must be online and cannot be promoted. // An example use case is the reader endpoint provided by cloud vendors. ReplicaAddress: []string{"reader_endpoint:port"}, }, SendToReplicas: func(cmd valkey.Completed) bool { return cmd.IsReadOnly() }, }) // Connect to a valkey cluster client, err := valkey.NewClient(valkey.ClientOption{ InitAddress: []string{"127.0.0.1:7001", "127.0.0.1:7002", "127.0.0.1:7003"}, ShuffleInit: true, }) // Connect to a valkey cluster and use replicas for read operations client, err := valkey.NewClient(valkey.ClientOption{ InitAddress: []string{"127.0.0.1:7001", "127.0.0.1:7002", "127.0.0.1:7003"}, SendToReplicas: func(cmd valkey.Completed) bool { return cmd.IsReadOnly() }, }) // Connect to sentinels client, err := valkey.NewClient(valkey.ClientOption{ InitAddress: []string{"127.0.0.1:26379", "127.0.0.1:26380", "127.0.0.1:26381"}, Sentinel: valkey.SentinelOption{ MasterSet: "my_master", }, }) // connect to valkey node through unix socket client, err := valkey.NewClient(valkey.ClientOption{ InitAddress: []string{"/run/valkey.sock"}, DialCtxFn: func(ctx context.Context, s string, d *net.Dialer, c *tls.Config) (conn net.Conn, err error) { return d.DialContext(ctx, "unix", s) }, }) ``` -------------------------------- ### Get string representation Source: https://pkg.go.dev/github.com/valkey-io/valkey-go Returns the human-readable representation of ValkeyMessage. ```go func (m *ValkeyMessage) String() string ``` -------------------------------- ### Initialize and Use a Valkey Locker Source: https://pkg.go.dev/github.com/valkey-io/valkey-go%40v1.0.76/valkeylock Demonstrates creating a new locker instance and acquiring a lock using WithContext. Ensure the locker is closed after use to release resources. ```go package main import ( "context" "github.com/valkey-io/valkey-go" "github.com/valkey-io/valkey-go/valkeylock" ) func main() { locker, err := valkeylock.NewLocker(valkeylock.LockerOption{ ClientOption: valkey.ClientOption{InitAddress: []string{"localhost:6379"}}, KeyMajority: 1, // Use KeyMajority=1 if you have only one Valkey instance. Also make sure that all your `Locker`s share the same KeyMajority. NoLoopTracking: true, // Enable this to have better performance if all your Valkey are >= 7.0.5. }) if err != nil { panic(err) } defer locker.Close() // acquire the lock "my_lock" ctx, cancel, err := locker.WithContext(context.Background(), "my_lock") if err != nil { panic(err) } // "my_lock" is acquired. use the ctx as normal. doSomething(ctx) // invoke cancel() to release the lock. cancel() } ``` -------------------------------- ### Get Time-Series Information Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Returns metadata and information about a time-series key. ```go func (c *Compat) TSInfo(ctx context.Context, key string) *MapStringInterfaceCmd ``` ```go func (c *Compat) TSInfoWithArgs(ctx context.Context, key string, options *TSInfoOptions) *MapStringInterfaceCmd ``` -------------------------------- ### JSON Get and Set Operations Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Methods for retrieving and updating JSON documents. ```go func (c *Compat) JSONGet(ctx context.Context, key string, paths ...string) *JSONCmd ``` ```go func (c *Compat) JSONGetWithArgs(ctx context.Context, key string, options *JSONGetArgs, paths ...string) *JSONCmd ``` ```go func (c *Compat) JSONMGet(ctx context.Context, path string, keys ...string) *JSONSliceCmd ``` ```go func (c *Compat) JSONMSet(ctx context.Context, params ...interface{}) *StatusCmd ``` ```go func (c *Compat) JSONMSetArgs(ctx context.Context, docs []JSONSetArgs) *StatusCmd ``` ```go func (c *Compat) JSONSet(ctx context.Context, key, path string, value interface{}) *StatusCmd ``` ```go func (c *Compat) JSONSetMode(ctx context.Context, key, path string, value interface{}, mode string) *StatusCmd ``` -------------------------------- ### Get Index Information Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Retrieves metadata and status information for a specified index. ```go func (c *Compat) FTInfo(ctx context.Context, index string) *FTInfoCmd ``` -------------------------------- ### Initialize a JSON Repository Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/om Creates a new JSON repository with a specified key prefix and schema. The schema must be a struct with fields tagged with valkey:",key". ```go func NewJSONRepository[T any](prefix string, schema T, client valkey.Client, opts ...RepositoryOption) Repository[T] ``` -------------------------------- ### Get required cache buffer size Source: https://pkg.go.dev/github.com/valkey-io/valkey-go Returns the buffer size needed by the CacheMarshal. ```go func (m *ValkeyMessage) CacheSize() int ``` -------------------------------- ### Pipeline Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Creates a new pipeline. ```go func (c *Compat) Pipeline() Pipeliner ``` -------------------------------- ### Get Pipeline Methods Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Methods for retrieving values and performing bit/range operations within a pipeline. ```go func (c *Pipeline) Get(ctx context.Context, key string) *StringCmd ``` ```go func (c *Pipeline) GetBit(ctx context.Context, key string, offset int64) *IntCmd ``` ```go func (c *Pipeline) GetDel(ctx context.Context, key string) *StringCmd ``` ```go func (c *Pipeline) GetEx(ctx context.Context, key string, expiration time.Duration) *StringCmd ``` ```go func (c *Pipeline) GetRange(ctx context.Context, key string, start, end int64) *StringCmd ``` ```go func (c *Pipeline) GetSet(ctx context.Context, key string, value any) *StringCmd ``` -------------------------------- ### Get Time-Series Sample Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Retrieves the last sample of a time-series key, optionally with additional arguments. ```go func (c *Compat) TSGet(ctx context.Context, key string) *TSTimestampValueCmd ``` ```go func (c *Compat) TSGetWithArgs(ctx context.Context, key string, options *TSGetOptions) *TSTimestampValueCmd ``` -------------------------------- ### Mock client.Do operations Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/mock Demonstrates how to use mock.Match and mock.Result to simulate Do and DoMulti command responses in a test environment. ```go package main import ( "context" "testing" "go.uber.org/mock/gomock" "github.com/valkey-io/valkey-go/mock" ) func TestWithValkey(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() ctx := context.Background() client := mock.NewClient(ctrl) client.EXPECT().Do(ctx, mock.Match("GET", "key")).Return(mock.Result(mock.ValkeyString("val"))) if v, _ := client.Do(ctx, client.B().Get().Key("key").Build()).ToString(); v != "val" { t.Fatalf("unexpected val %v", v) } client.EXPECT().DoMulti(ctx, mock.Match("GET", "c"), mock.Match("GET", "d")).Return([]valkey.ValkeyResult{ mock.Result(mock.ValkeyNil()), mock.Result(mock.ValkeyNil()), }) for _, resp := range client.DoMulti(ctx, client.B().Get().Key("c").Build(), client.B().Get().Key("d").Build()) { if err := resp.Error(); !valkey.IsValkeyNil(err) { t.Fatalf("unexpected err %v", err) } } } ``` -------------------------------- ### Get client-side cache TTL Source: https://pkg.go.dev/github.com/valkey-io/valkey-go Returns the remaining TTL in seconds of client side cache. ```go func (m *ValkeyMessage) CacheTTL() (ttl int64) ``` -------------------------------- ### Create a new RateLimiter Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeylimiter Initialization of the rate limiter with specific options. ```go limiter, err := valkeylimiter.NewRateLimiter(valkeylimiter.RateLimiterOption{ ClientOption: valkey.ClientOption{InitAddress: []string{"localhost:6379"}}, KeyPrefix: "api_rate_limit", Limit: 5, Window: time.Second, }) ``` -------------------------------- ### Get client-side cache PXAT Source: https://pkg.go.dev/github.com/valkey-io/valkey-go Returns the remaining PXAT in seconds of client side cache. ```go func (m *ValkeyMessage) CachePXAT() int64 ``` -------------------------------- ### Explain Query Execution Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Retrieves the execution plan for a query, with optional configuration arguments. ```go func (c *Compat) FTExplain(ctx context.Context, index string, query string) *StringCmd ``` ```go func (c *Compat) FTExplainWithArgs(ctx context.Context, index string, query string, options *FTExplainOptions) *StringCmd ``` -------------------------------- ### Get client-side cache PTTL Source: https://pkg.go.dev/github.com/valkey-io/valkey-go Returns the remaining PTTL in seconds of client side cache. ```go func (m *ValkeyMessage) CachePTTL() int64 ``` -------------------------------- ### FTExplainOptions Struct Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Options for the FT.EXPLAIN command. ```go type FTExplainOptions struct { Dialect string } ``` -------------------------------- ### Implement and Apply a Custom Hook Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeyhook Demonstrates implementing the Hook interface to intercept client commands and applying it using valkeyhook.WithHook. ```go package main import ( "context" "time" "github.com/valkey-io/valkey-go" "github.com/valkey-io/valkey-go/valkeyhook" ) type hook struct{} func (h *hook) Do(client valkey.Client, ctx context.Context, cmd valkey.Completed) (resp valkey.ValkeyResult) { // do whatever you want before a client.Do resp = client.Do(ctx, cmd) // do whatever you want after a client.Do return } func (h *hook) DoMulti(client valkey.Client, ctx context.Context, multi ...valkey.Completed) (resps []valkey.ValkeyResult) { // do whatever you want before a client.DoMulti resps = client.DoMulti(ctx, multi...) // do whatever you want after a client.DoMulti return } func (h *hook) DoCache(client valkey.Client, ctx context.Context, cmd valkey.Cacheable, ttl time.Duration) (resp valkey.ValkeyResult) { // do whatever you want before a client.DoCache resp = client.DoCache(ctx, cmd, ttl) // do whatever you want after a client.DoCache return } func (h *hook) DoMultiCache(client valkey.Client, ctx context.Context, multi ...valkey.CacheableTTL) (resps []valkey.ValkeyResult) { // do whatever you want before a client.DoMultiCache resps = client.DoMultiCache(ctx, multi...) // do whatever you want after a client.DoMultiCache return } func (h *hook) Receive(client valkey.Client, ctx context.Context, subscribe valkey.Completed, fn func(msg valkey.PubSubMessage)) (err error) { // do whatever you want before a client.Receive err = client.Receive(ctx, subscribe, fn) // do whatever you want after a client.Receive return } func main() { client, err := valkey.NewClient(valkey.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}) if err != nil { panic(err) } client = valkeyhook.WithHook(client, &hook{}) defer client.Close() } ``` -------------------------------- ### Get Multiple Time-Series Samples Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Returns the last sample of multiple time-series keys based on filters. ```go func (c *Compat) TSMGet(ctx context.Context, filters []string) *MapStringSliceInterfaceCmd ``` ```go func (c *Compat) TSMGetWithArgs(ctx context.Context, filters []string, options *TSMGetOptions) *MapStringSliceInterfaceCmd ``` -------------------------------- ### Pipelining with valkeycompat Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Execute multiple commands in a single network round-trip using the Pipelined method. ```go package main import ( "context" "fmt" "github.com/valkey-io/valkey-go" "github.com/valkey-io/valkey-go/valkeycompat" ) func main() { ctx := context.Background() client, err := valkey.NewClient(valkey.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}) if err != nil { panic(err) } defer client.Close() rdb := valkeycompat.NewAdapter(client) cmds, err := rdb.Pipelined(ctx, func(pipe valkeycompat.Pipeliner) error { for i := 0; i < 100; i++ { pipe.Set(ctx, fmt.Sprintf("key%d", i), i, 0) pipe.Get(ctx, fmt.Sprintf("key%d", i)) } return nil }) if err != nil { panic(err) } for _, cmd := range cmds { fmt.Println(cmd.(*valkeycompat.StringCmd).Val()) } } ``` -------------------------------- ### Client Configuration Options Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeyaside Configuration struct for customizing the cache-aside client behavior. ```go type ClientOption struct { // ClientBuilder can be used to modify valkey.Client used by Locker ClientBuilder func(option valkey.ClientOption) (valkey.Client, error) ClientOption valkey.ClientOption ClientTTL time.Duration // TTL for the client marker, refreshed every 1/2 TTL. Defaults to 10s. The marker allows other clients to know if this client is still alive. UseLuaLock bool } ``` -------------------------------- ### CacheAsideClient Interface Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeyaside Defines the core methods for cache-aside operations including Get, Del, and client management. ```go type CacheAsideClient interface { Get(ctx context.Context, ttl time.Duration, key string, fn func(ctx context.Context, key string) (val string, err error)) (val string, err error) Del(ctx context.Context, key string) error Client() valkey.Client Close() } ``` -------------------------------- ### Initialize CacheAsideClient Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeyaside Creates a new instance of the cache-aside client. ```go func NewClient(option ClientOption) (cc CacheAsideClient, err error) ``` -------------------------------- ### Initialize NewAdapter Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompatmock Creates a new mock adapter instance from a mock client. ```go func NewAdapter(m *mock.Client) *ClientMock ``` -------------------------------- ### FTCreateOptions Struct Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Configuration options for creating a search index in Valkey. ```go type FTCreateOptions struct { Filter string DefaultLanguage string LanguageField string ScoreField string PayloadField string Prefix []any StopWords []any Score float64 MaxTextFields int Temporary int OnHash bool OnJSON bool NoOffsets bool NoHL bool NoFields bool NoFreqs bool SkipInitialScan bool } ``` -------------------------------- ### Batch key operations Source: https://pkg.go.dev/github.com/valkey-io/valkey-go Helper functions for performing multi-key operations like delete, get, set, and set-if-not-exists. ```go func MDel(client Client, ctx context.Context, keys []string) map[string]error ``` ```go func MGet(client Client, ctx context.Context, keys []string) (ret map[string]ValkeyMessage, err error) ``` ```go func MGetCache(client Client, ctx context.Context, ttl time.Duration, keys []string) (ret map[string]ValkeyMessage, err error) ``` ```go func MSet(client Client, ctx context.Context, kvs map[string]string) map[string]error ``` ```go func MSetNX(client Client, ctx context.Context, kvs map[string]string) map[string]error ``` -------------------------------- ### Initialize and use a Counting Bloom Filter Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeyprob Shows how to use a Counting Bloom Filter to add, check, count, and remove elements. ```go package main import ( "context" "fmt" "github.com/valkey-io/valkey-go" "github.com/valkey-io/valkey-go/valkeyprob" ) func main() { client, err := valkey.NewClient(valkey.ClientOption{ InitAddress: []string{"localhost:6379"}, }) if err != nil { panic(err) } cbf, err := valkeyprob.NewCountingBloomFilter(client, "counting_bloom_filter", 1000, 0.01) err = cbf.Add(context.Background(), "hello") if err != nil { panic(err) } err = cbf.Add(context.Background(), "world") if err != nil { panic(err) } exists, err := cbf.Exists(context.Background(), "hello") if err != nil { panic(err) } fmt.Println(exists) // true exists, err = cbf.Exists(context.Background(), "world") if err != nil { panic(err) } fmt.Println(exists) // true count, err := cbf.Count(context.Background()) if err != nil { panic(err) } fmt.Println(count) // 2 err = cbf.Remove(context.Background(), "hello") if err != nil { panic(err) } exists, err = cbf.Exists(context.Background(), "hello") if err != nil { panic(err) } fmt.Println(exists) // false count, err = cbf.Count(context.Background()) if err != nil { panic(err) } fmt.Println(count) // 1 } ``` -------------------------------- ### Initialize and use a Sliding Window Bloom Filter Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeyprob Demonstrates using a Sliding Window Bloom Filter to track items over a specific time duration. ```go package main import ( "context" "fmt" "time" "github.com/valkey-io/valkey-go" "github.com/valkey-io/valkey-go/valkeyprob" ) func main() { client, err := valkey.NewClient(valkey.ClientOption{ InitAddress: []string{"localhost:6379"}, }) if err != nil { panic(err) } sbf, err := NewSlidingBloomFilter(client, "sliding_bloom_filter", 1000, 0.01, time.Minute) err = sbf.Add(context.Background(), "hello") if err != nil { panic(err) } err = sbf.Add(context.Background(), "world") if err != nil { panic(err) } exists, err := sbf.Exists(context.Background(), "hello") if err != nil { panic(err) } fmt.Println(exists) // true exists, err = sbf.Exists(context.Background(), "world") if err != nil { panic(err) } fmt.Println(exists) // true count, err := sbf.Count(context.Background()) if err != nil { panic(err) } fmt.Println(count) // 2 } ``` -------------------------------- ### Pipeline Server and Key Management Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Methods for server status, key metadata, and data migration. ```go func (c *Pipeline) LastSave(ctx context.Context) *IntCmd ``` ```go func (c *Pipeline) MemoryUsage(ctx context.Context, key string, samples ...int64) *IntCmd ``` ```go func (c *Pipeline) Migrate(ctx context.Context, host string, port int64, key string, db int64, timeout time.Duration) *StatusCmd ``` ```go func (c *Pipeline) Move(ctx context.Context, key string, db int64) *BoolCmd ``` ```go func (c *Pipeline) ObjectEncoding(ctx context.Context, key string) *StringCmd ``` ```go func (c *Pipeline) ObjectIdleTime(ctx context.Context, key string) *DurationCmd ``` ```go func (c *Pipeline) ObjectRefCount(ctx context.Context, key string) *IntCmd ``` ```go func (c *Pipeline) Ping(ctx context.Context) *StatusCmd ``` ```go func (c *Pipeline) Quit(ctx context.Context) *StatusCmd ``` -------------------------------- ### Benchmark Auto Pipelining Source: https://pkg.go.dev/github.com/valkey-io/valkey-go Demonstrates how concurrent client.Do calls from multiple goroutines are automatically pipelined. ```go func BenchmarkPipelining(b *testing.B, client valkey.Client) { // the below client.Do() operations will be issued from // multiple goroutines and thus will be pipelined automatically. b.RunParallel(func(pb *testing.PB) { for pb.Next() { client.Do(context.Background(), client.B().Get().Key("k").Build()).ToString() } }) } ``` -------------------------------- ### func MGet(client Client, ctx context.Context, keys []string) (ret map[string]ValkeyMessage, err error) Source: https://pkg.go.dev/github.com/valkey-io/valkey-go Consults Valkey directly with multiple keys by grouping them into MGET or multiple GETs. ```APIDOC ## func MGet(client Client, ctx context.Context, keys []string) (ret map[string]ValkeyMessage, err error) ### Description Consults the valkey directly with multiple keys by grouping keys within the same slot into MGET or multiple GETs. ``` -------------------------------- ### NewHashRepository constructor Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/om Initializes a new HashRepository with a specific prefix and schema. ```go func NewHashRepository[T any](prefix string, schema T, client valkey.Client, opts ...RepositoryOption) Repository[T] ``` -------------------------------- ### func MGetCache(client Client, ctx context.Context, ttl time.Duration, keys []string) (ret map[string]ValkeyMessage, err error) Source: https://pkg.go.dev/github.com/valkey-io/valkey-go Consults client-side caches with multiple keys by grouping them into multiple GETs. ```APIDOC ## func MGetCache(client Client, ctx context.Context, ttl time.Duration, keys []string) (ret map[string]ValkeyMessage, err error) ### Description Consults the client-side caches with multiple keys by grouping keys within the same slot into multiple GETs. ``` -------------------------------- ### Server Management Commands Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Methods for background server operations. ```go func (c *Compat) BgRewriteAOF(ctx context.Context) *StatusCmd ``` ```go func (c *Compat) BgSave(ctx context.Context) *StatusCmd ``` -------------------------------- ### PubSub with valkeycompat Source: https://pkg.go.dev/github.com/valkey-io/valkey-go/valkeycompat Subscribe to channels and receive messages using the PubSub interface. ```go package main import ( "context" "fmt" "github.com/valkey-io/valkey-go" "github.com/valkey-io/valkey-go/valkeycompat" "strconv" ) func main() { ctx := context.Background() client, err := valkey.NewClient(valkey.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}) if err != nil { panic(err) } defer client.Close() rdb := valkeycompat.NewAdapter(client) pubsub := rdb.Subscribe(ctx, "mychannel1") defer pubsub.Close() go func() { for i := 0; ; i++ { if err := rdb.Publish(ctx, "mychannel1", strconv.Itoa(i)).Err(); err != nil { panic(err) } } }() for { msg, err := pubsub.ReceiveMessage(ctx) if err != nil { panic(err) } fmt.Println(msg.Channel, msg.Payload) } } ```