Memcached – Incr/Decr


Memcached – Increment Decrement Data


”;


Memcached incr and decr commands are used to increment or decrement the numeric value of an existing key. If the key is not found, then it returns NOT_FOUND. If the key is not numeric, then it returns CLIENT_ERROR cannot increment or decrement non-numeric value. Otherwise, ERROR is returned.

Syntax – incr

The basic syntax of Memcached incr command is as shown below −

incr key increment_value

Example

In this example, we use visitors as key and set 10 initially into it, thereafter we increment the visitors by 5.

set visitors 0 900 2
10
STORED
get visitors
VALUE visitors 0 2
10
END
incr visitors 5
15
get visitors
VALUE visitors 0 2
15
END

Syntax – decr

The basic syntax of Memcached decr command is as shown below

decr key decrement_value

Example

set visitors 0 900 2
10
STORED
get visitors
VALUE visitors 0 2
10
END
decr visitors 5
5
get visitors
VALUE visitors 0 1
5
END

Incr/Decr Using Java Application

To increment or decrement data in a Memcached server, you need to use Memcached incr or decr methods respectively.

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("count", 900, "5").isDone());
      
      // Get value from cache
      System.out.println("Get from Cache:"+mcc.get("count"));
      
      // now increase the stored value
      System.out.println("Increment value:"+mcc.incr("count", 2));
      
      // now decrease the stored value
      System.out.println("Decrement value:"+mcc.decr("count", 1));
      
      // now get the final stored value
      System.out.println("Get from Cache:"+mcc.get("count"));
   }
}

Output

On compiling and executing the program, you get to see the following output −

Connection to server successfully
set status:true
Get from Cache:5
Increment value:7
Decrement value:6
Get from Cache:6

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *