Memcached stats provide valuable information about the state of your cache. They can be used for:
We use gomemcache
, the Memcached client library for Go.
Example 1: Get basic stats
package main import ( "github.com/bradfitz/gomemcache/memcache" "fmt" ) func main() { mc := memcache.New("localhost:11211") // connect to memcache server stats, err := mc.Stats() // get stats from server if err != nil { fmt.Println(err) return } fmt.Printf("%+v\n", stats) // print all stats }
In this example, we first establish a connection to the Memcached server using its address (in this case, localhost on port 11211). We then fetch the stats using mc.Stats()
and print them.
Example 2: Get specific stat
package main import ( "github.com/bradfitz/gomemcache/memcache" "fmt" ) func main() { mc := memcache.New("localhost:11211") // connect to memcache server stats, err := mc.Stats() // get stats from server if err != nil { fmt.Println(err) return } fmt.Printf("Cache Hits: %s\n", stats["get_hits"]) // print cache hits stat }
In this example, we fetch a specific stat (get_hits
), providing the number of successful get commands.
Not checking for errors: When using mc.Stats()
, an error can be returned for a variety of reasons (e.g., network issues, incorrect server address). Always handle these potential errors in your code.
Q1: Can I get other stats like memory usage?
Yes, you can get any of the stats that Memcached provides such as total memory, used memory, hit ratios etc. The exact stat name is what you provide as the key to the stats dictionary.
Q2: How often should I fetch Memcached stats?
The answer depends on your specific use case. If you're debugging an issue or monitoring load on your cache, you might do it more frequently. In production systems, fetching every 5-10 minutes is pretty standard.
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.