Memcached - Stats
Memcached - Monitoring with Stats
Section titled “Memcached - Monitoring with Stats”The stats command is a powerful diagnostic tool that provides a wide range of metrics about the Memcached server’s performance and state. Monitoring these statistics is crucial for understanding cache behavior, diagnosing issues, and optimizing performance.
Syntax
Section titled “Syntax”You can get general statistics by connecting via telnet and running:
statsExample Output and Key Metrics Explained
Section titled “Example Output and Key Metrics Explained”The stats command produces a long list of key-value pairs. Here are some of the most important ones and what they mean:
STAT cmd_get 8734STAT cmd_set 1245STAT get_hits 7988STAT get_misses 746STAT evictions 152STAT curr_items 980STAT total_items 1245STAT bytes 874320STAT curr_connections 10STAT total_connections 54STAT rusage_user 0.542012STAT rusage_system 0.899345ENDcmd_get/cmd_set: Total number ofgetandsetcommands received. Helps understand the read/write ratio of your cache.get_hits: Number of times agetrequest found the data. A high number is good.get_misses: Number of times agetrequest did not find the data. This means the application had to fall back to the primary data source (e.g., a database).evictions: Number of valid, non-expired items removed from the cache to make space for new items because the cache was full. A high or rapidly growing number of evictions is a strong indicator that you need to allocate more memory to Memcached.curr_items: The current number of items stored in the cache.bytes: The current number of bytes used to store items.curr_connections: The number of currently open connections to the server.- Cache Hit Ratio: A critical performance metric you can calculate:
(get_hits / cmd_get) * 100. A good hit ratio is typically > 90-95%, but this varies by application.
Getting Stats with a Modern Java Client
Section titled “Getting Stats with a Modern Java Client”Client libraries provide a method to fetch and parse these statistics, allowing you to build monitoring and alerting into your application.
1. Add Dependency
Section titled “1. Add Dependency”Ensure the spymemcached dependency is in your Maven pom.xml:
<dependency> <groupId>net.spy</groupId> <artifactId>spymemcached</artifactId> <version>2.12.3</version></dependency>2. Java Code Example
Section titled “2. Java Code Example”Instead of printing the raw map of stats, this example retrieves the stats, calculates the cache hit ratio, and displays a few key metrics in a clean, human-readable format.
import net.spy.memcached.MemcachedClient;import net.spy.memcached.AddrUtil;
import java.io.IOException;import java.net.SocketAddress;import java.util.Map;
public class MemcachedStatsExample { public static void main(String[] args) { String serverAddress = "127.0.0.1:11211";
try (MemcachedClient client = new MemcachedClient(AddrUtil.getAddresses(serverAddress))) { System.out.println("Connection to Memcached server successful.\n");
// The getStats() method returns a map of server addresses to their stats maps. Map<SocketAddress, Map<String, String>> stats = client.getStats();
// Iterate over each server's stats (in this case, just one) for (Map.Entry<SocketAddress, Map<String, String>> entry : stats.entrySet()) { System.out.println("--- Stats for server: " + entry.getKey() + " ---"); Map<String, String> serverStats = entry.getValue();
// Extract key metrics long getCmds = Long.parseLong(serverStats.getOrDefault("cmd_get", "0")); long getHits = Long.parseLong(serverStats.getOrDefault("get_hits", "0")); long evictions = Long.parseLong(serverStats.getOrDefault("evictions", "0")); long currItems = Long.parseLong(serverStats.getOrDefault("curr_items", "0")); long totalConnections = Long.parseLong(serverStats.getOrDefault("total_connections", "0"));
// Calculate Cache Hit Ratio double hitRatio = (getCmds == 0) ? 0.0 : ((double) getHits / getCmds) * 100;
// Display formatted stats System.out.printf("Cache Hit Ratio: %.2f%%\n", hitRatio); System.out.printf("Total Get Commands: %d\n", getCmds); System.out.printf("Total Get Hits: %d\n", getHits); System.out.printf("Current Items in Cache: %d\n", currItems); System.out.printf("Total Items Evicted: %d\n", evictions); System.out.printf("Total Connections since start: %d\n", totalConnections); }
} catch (IOException e) { System.err.println("An error occurred: " + e.getMessage()); } }}Output
Section titled “Output”The output will be a neatly formatted summary of the server’s health:
Connection to Memcached server successful.
--- Stats for server: /127.0.0.1:11211 ---Cache Hit Ratio: 91.50%Total Get Commands: 8734Total Get Hits: 7988Current Items in Cache: 980Total Items Evicted: 152Total Connections since start: 54