Skip to content

Memcached - Connection

Connecting to a Memcached server is the first step in using it as a cache. For basic debugging and learning, you can connect using a simple command-line tool like telnet. In your applications, you will use a language-specific client library that handles the protocol, connections, and data serialization for you.

Prerequisites: Running a Memcached Instance

Section titled “Prerequisites: Running a Memcached Instance”

Before you can connect, you need a running Memcached server. For local development, the easiest way to start one is by using Docker. This command will start a Memcached server and expose it on the default port, 11211.

docker run --name my-memcache -p 11211:11211 -d memcached:1.6-alpine

Connecting via Command Line (for Debugging)

Section titled “Connecting via Command Line (for Debugging)”

You can use telnet to connect directly to the Memcached server. This is useful for manually checking values or understanding the raw Memcached text protocol.

telnet HOST PORT

Here, HOST is the server IP (e.g., 127.0.0.1 for localhost) and PORT is the port number (typically 11211).

$ telnet 127.0.0.1 11211
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
# Now you can issue Memcached commands directly
# Format: set <key> <flags> <exptime> <bytes> [noreply]
set w3 0 900 9
memcached
STORED
get w3
VALUE w3 0 9
memcached
END

In a Java application, you should use a client library to manage connections. spymemcached is a popular choice. First, add it as a dependency in your project.

<dependency>
<groupId>net.spy</groupId>
<artifactId>spymemcached</artifactId>
<version>2.12.3</version>
</dependency>
import net.spy.memcached.MemcachedClient;
import java.net.InetSocketAddress;
import java.util.concurrent.Future;
import java.io.IOException;
public class MemcachedConnectionExample {
public static void main(String[] args) {
String serverAddress = "127.0.0.1";
int port = 11211;
MemcachedClient mcc = null;
try {
// Establish a connection to the Memcached server
mcc = new MemcachedClient(new InetSocketAddress(serverAddress, port));
System.out.println("Connection to server successful.");
// Set a key-value pair. The operation is asynchronous and returns a Future.
Future<Boolean> setFuture = mcc.set("w3", 900, "memcached");
// To confirm the operation, we can block and wait for the result.
if (setFuture.get()) { // .get() waits for the operation to complete
System.out.println("Set operation successful.");
} else {
System.err.println("Set operation failed.");
}
// Get the value from the cache
Object value = mcc.get("w3");
System.out.println("Get from Cache: " + value);
} catch (IOException e) {
System.err.println("Couldn't establish a connection to Memcached: " + e.getMessage());
} catch (Exception e) {
// Future.get() can throw InterruptedException or ExecutionException
System.err.println("An error occurred during a cache operation: " + e.getMessage());
} finally {
// It's crucial to shut down the client to release resources and connections.
if (mcc != null) {
mcc.shutdown();
}
}
}
}
Connection to server successful.
Set operation successful.
Get from Cache: memcached

Client Configuration: For production, instantiate the client once and share it across your application (it is thread-safe). Configure timeouts and operation queues appropriately for your workload.

Security: Memcached has no built-in authentication or encryption. It should always be run on a trusted, private network, firewalled from public access.

Error Handling: A robust application must handle cache unavailability gracefully. If the Memcached client cannot connect, the application should fall back to fetching data from the primary source without crashing.