Memcached 简明教程
Memcached - Increment Decrement Data
Memcached incr 和 decr 命令用于增加或减少现有密钥的数值。如果未找到该密钥,则它将返回 NOT_FOUND 。如果该密钥不是数字,则它将返回 CLIENT_ERROR cannot increment or decrement non-numeric value 。否则,将返回 ERROR 。
Example
在此示例中,我们使用 visitors 作为密钥,并最初在其中设置 10,然后将其增加 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
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
若要在 Memcached 服务器中增加或减少数据,您需要分别使用 Memcached incr or decr 方法。
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"));
}
}