Golang: Using Memcached

09 Sep 2014 in TIL

If you want to use memcached in a Golang project, the most recommended library is is memcache from Brad Fitzpatrick. Brad is both the author of memcache and a Golang core team member, which means that we can trust the library that he wrote.

Installation

First, we need to install the library:

bash
go get github.com/bradfitz/gomemcache/memcache

Cheatsheet

Here's the minimum you need to know to use memcached

Connect to memcache

go
mc := memcache.New("127.0.0.1:11211")
// => memcache.Client (http://godoc.org/github.com/bradfitz/gomemcache/memcache#Client)

Set a value

go
err := mc.Set(&memcache.Item{Key: "key_one", Value: []byte("michael")})
// => Error

Get a value

go
val, err := mc.Get("key_one")
// => memcache.Item, Error

Get multiple values

go
it, err := mc.GetMulti([]string{"key_one", "key_two"})
// => map[string]memcache.Item, Error

Putting it all together

Then we can write a small program to talk to our memcached server

go
package main
import (
"fmt"
"github.com/bradfitz/gomemcache/memcache"
)
func main() {
// Connect to our memcache instance
mc := memcache.New("127.0.0.1:11211")
// Set some values
mc.Set(&memcache.Item{Key: "key_one", Value: []byte("michael")})
mc.Set(&memcache.Item{Key: "key_two", Value: []byte("programming")})
// Get a single value
val, err := mc.Get("key_one")
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("-- %s", val.Value)
// Get multiple values
it, err := mc.GetMulti([]string{"key_one", "key_two"})
if err != nil {
fmt.Println(err)
return
}
// It's important to note here that `range` iterates in a *random* order
for k, v := range it {
fmt.Printf("## %s => %s\n", k, v.Value)
}
}

The return values from memcache will be wrapped in a memcache.Item type. You can find the documentation that shows it's properties here