Memcached - Delete Data
Memcached - Deleting Data
Section titled “Memcached - Deleting Data”The delete command removes an existing key-value pair from the Memcached server. This operation is fundamental for cache invalidation strategies.
Syntax
Section titled “Syntax”The basic syntax for the delete command via a telnet connection is:
delete key [noreply]The server will respond with one of the following:
DELETED: The key was found and successfully removed.NOT_FOUND: The key did not exist on the server.ERROR: Indicates an error in the command syntax.
Command Line Example
Section titled “Command Line Example”In this example, we’ll use telnet to connect to a Memcached server. First, we set a key named session_token, verify it exists, delete it, and then verify it’s gone.
# First, set a key-value pairset session_token 0 3600 36xyz-abc-123-789-pqr-lmn-456-defSTORED
# Retrieve the key to confirm it's thereget session_tokenVALUE session_token 0 36xyz-abc-123-789-pqr-lmn-456-defEND
# Now, delete the keydelete session_tokenDELETED
# Try to retrieve the key againget session_tokenEND
# Try to delete the same key againdelete session_tokenNOT_FOUNDDeleting Data with a Modern Java Client
Section titled “Deleting Data with a Modern Java Client”In a real-world application, you’ll use a client library to interact with Memcached. Here, we’ll use spymemcached, a popular Java client. The modern approach is to manage dependencies with a build tool like Maven or Gradle and to handle resources safely.
1. Add Dependency
Section titled “1. Add Dependency”Add the spymemcached dependency to your pom.xml if you are using Maven:
<dependency> <groupId>net.spy</groupId> <artifactId>spymemcached</artifactId> <version>2.12.3</version> <!-- Use the latest stable version --></dependency>2. Java Code Example
Section titled “2. Java Code Example”This example demonstrates how to connect to the server, set a value, confirm its existence, delete it, and then confirm its deletion. We use a try-with-resources block to ensure the client connection is always closed properly.
import net.spy.memcached.MemcachedClient;import net.spy.memcached.AddrUtil;import net.spy.memcached.internal.OperationFuture;
import java.io.IOException;import java.util.concurrent.ExecutionException;
public class MemcachedDeleteExample { public static void main(String[] args) { String serverAddress = "127.0.0.1:11211"; String key = "user:123:profile"; String value = "{"name":"John Doe", "email":"john.doe@example.com"}"; int expiration = 3600; // 1 hour
try (MemcachedClient client = new MemcachedClient(AddrUtil.getAddresses(serverAddress))) { System.out.println("Connection to Memcached server successful.");
// 1. Set a value to be deleted later OperationFuture<Boolean> setFuture = client.set(key, expiration, value); if (setFuture.get()) { System.out.println("Successfully set key '" + key + "'."); } else { System.err.println("Failed to set key '" + key + "'."); return; }
// 2. Verify the value exists Object retrievedValue = client.get(key); System.out.println("Retrieved value before delete: " + retrievedValue);
// 3. Delete the value OperationFuture<Boolean> deleteFuture = client.delete(key); if (deleteFuture.get()) { System.out.println("Successfully deleted key '" + key + "'."); } else { System.out.println("Failed to delete key '" + key + "' (it may not have existed)."); }
// 4. Verify the value is now null retrievedValue = client.get(key); System.out.println("Retrieved value after delete: " + retrievedValue);
} catch (IOException | InterruptedException | ExecutionException e) { System.err.println("An error occurred: " + e.getMessage()); // In a real app, you would log this exception Thread.currentThread().interrupt(); } }}Output
Section titled “Output”When you compile and run the above program, you should see the following output:
Connection to Memcached server successful.Successfully set key 'user:123:profile'.Retrieved value before delete: {"name":"John Doe", "email":"john.doe@example.com"}Successfully deleted key 'user:123:profile'.Retrieved value after delete: nullBest Practices
Section titled “Best Practices”- Cache Invalidation: Use
deleteto remove stale data from the cache when the source of truth (e.g., a database record) is updated or deleted. - Error Handling: The
Futurereturned bydeletecan fail. Always check the result and handle potential exceptions to build a robust application. - Resource Management: Always close your Memcached client connection to release network resources. Using a
try-with-resourcesstatement is the recommended way to do this in Java.