Skip to content

Memcached - Get Data

The get command is the primary way to retrieve a single item from the Memcached cache using its key. If the key exists, the server returns the stored data. If the key does not exist (a ‘cache miss’), the server returns nothing, and client libraries typically represent this as a null value.

The basic syntax of the Memcached get command is straightforward:

get key

In this example, we use w3 as the key and store the string memcached in it with an expiration time of 900 seconds.

# First, set a key so we have something to retrieve
set w3 0 900 9
memcached
STORED
# Now, get the data associated with the key
get w3
VALUE w3 0 9
memcached
END

Using the spymemcached Java client, the get method retrieves an object from the cache. A crucial part of application logic is to always check if the result is null, which indicates a cache miss. This allows the application to then fetch the data from the primary data source (like a database) and populate the cache.

import net.spy.memcached.MemcachedClient;
import java.net.InetSocketAddress;
import java.util.concurrent.Future;
public class GetDataExample {
public static void main(String[] args) {
MemcachedClient mcc = null;
try {
mcc = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
System.out.println("Connection to server successful.");
// First, store a value so we can retrieve it
Future<Boolean> setFuture = mcc.set("language", 900, "Java");
setFuture.get(); // Wait for the set operation to complete
// --- CACHE HIT EXAMPLE ---
System.out.println("\nAttempting to get key 'language'...");
Object value = mcc.get("language");
// Check for a cache hit or miss
if (value != null) {
System.out.println("Cache Hit! Key: 'language', Value: '" + value + "'");
} else {
System.out.println("Cache Miss! Key 'language' not found.");
}
// --- CACHE MISS EXAMPLE ---
System.out.println("\nAttempting to get a non-existent key...");
Object missingValue = mcc.get("non_existent_key");
if (missingValue != null) {
System.out.println("Cache Hit! Key: 'non_existent_key', Value: '" + missingValue + "'");
} else {
System.out.println("Cache Miss! Key 'non_existent_key' not found.");
}
} catch (Exception e) {
System.err.println("An error occurred: " + e.getMessage());
} finally {
if (mcc != null) {
mcc.shutdown();
}
}
}
}
Connection to server successful.
Attempting to get key 'language'...
Cache Hit! Key: 'language', Value: 'Java'
Attempting to get a non-existent key...
Cache Miss! Key 'non_existent_key' not found.

Practical Use Case: The Cache-Aside Pattern

Section titled “Practical Use Case: The Cache-Aside Pattern”

The most common use for caching is to reduce database load and improve application response times. The ‘Cache-Aside’ pattern is a standard strategy for achieving this.

function getUserProfile(userId) {
const cacheKey = `user:${userId}:profile`;
// 1. Check the cache first
let profile = cache.get(cacheKey);
if (profile !== null) {
// 2. Cache Hit: The data was found in the cache. Return it immediately.
console.log("Cache Hit!");
return profile;
} else {
// 3. Cache Miss: The data was not in the cache.
console.log("Cache Miss. Fetching from database...");
// 4. Query the primary data source (e.g., a database).
profile = database.query("SELECT * FROM profiles WHERE user_id = ?", userId);
// 5. Store the result in the cache for subsequent requests.
if (profile) {
cache.set(cacheKey, profile, 3600); // Cache for 1 hour
}
return profile;
}
}