memc is a modern and generics enabled memcached client library for Go.
requires go1.23+
October 2024: (!) This package is very new and may contain bugs and missing features.
The memc package can be added to a Go project with go get.
go get cattlecloud.net/go/memc@latestimport "cattlecloud.net/go/memc"Supports connecting via TCP or Unix Domain Socket.
client := memc.New(
[]string{"localhost:11211"},
)For sockets, simply specify the socket filepath.
client := memc.New(
[]string{"/var/lib/app/cache.socket"},
)err := memc.Set(client, "my/key/name", "some_value")Note that the memc library can handle arbitrary value types, as long as they
can be encoded using Go's built-in gob package. The library automatically
handles serialization on writes and de-serialization on reads.
err := memc.Set(client, "my/key/name", &Person{Name: "Bob"})The memc package will automatically convert the value []byte into the type
of your Go variable.
value, err := memc.Get[T](client, "my/key/name")The memc package provides Increment and Decrement for increasing or
decreasing a value by a given delta. Note that the value must already be stored,
and must be in the form of an ASCII string representation of a number. The delta
value must be positive.
err := memc.Set(client, "/my/counter", "100")Using Increment to increase the counter value by 1.
v, err := memc.Increment("/my/counter", 1)
// v is now 101Using Decrement to decrease the value by 5.
v, err := memc.Decrement("/my/counter", 5)
// v is now 96The memcached can handle sharding writes and reads across multiple memcached
instances. It does this by hashing the key space and deterministically choosing
an assigned instance. To enable this behavior simply give the Client each
memcached instance address.
client := memc.New(
[]string{
"10.0.0.1:11211",
"10.0.0.2:11211",
"10.0.0.3:11211",
},
)The Client sets a default expiration time on each value. This expiration time
can be configured when creating the client.
client := memc.New(
// ...
SetDefaultTTL(2 * time.Minute),
)The Client maintains an idle connection pool for each memcached instance it
has connected to. The number of idle connections to maintain per instance can be
adjusted.
client := memc.New(
// ...
SetIdleConnections(4),
)The Client can be closed so that idle connections are closed and no longer
consuming resources. In-flight requests will be closed once complete. Once
closed the client cannot be reused.
_ = memc.Close()The cattlecloud.net/go/memc module is open source under the BSD-3-Clause license.