Written by - Yash Agrawal

How to set data in memcached


This is the most common command in memcached for storing data or overwrites the existing data in the particular key. New items are stored at the top of the LRU (Least Recently Used).

set key flags exptime bytes [noreply]  
value  
Let's understand the syntax:

  1. key: It is the key to the data stored and retrieved from Memcached.
  2. flags: It is the 32-bit unsigned integer that the server stores with the data (provided by the user), and returns along with the data when the item is retrieved.
  3. exptime: exptime is expiration time in seconds. 0 means no delay. If it is more than 30 days, Memcached uses it as UNIX timestamp for expiration.
  4. bytes: It is the number of bytes in the data block that needs to be stored. This is the length of the data that is stored in Memcached.
  5. noreply: It is an optional parameter. It is used to inform the server not to send any reply.
  6. value: It is the data that have to be stored. The data needs to be passed on the new line after executing the command with the above options.

Memcached can be used with programming languages. Mostly it is used in servers to reduce database load.

Here is the Java code example.

import net.spy.memcached.MemcachedClient;  
public class MemcachedJava {  
  public static void main(String[] args) {  
      
    // Connecting to Memcached server on localhost  
    MemcachedClient mcc = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));  
    System.out.println("Connection to server sucessfully");  
      
    System.out.println("set status:"+mcc.set("city", 900, "Bangalore").done);  
      
    //Get value from cache  
    System.out.println("Get from Cache:"+mcc.get("Bangalore"));  
  }  
}