📅  最后修改于: 2020-11-27 05:45:37             🧑  作者: Mango
Memcached的incr和decr命令用于递增或递减现有键的数值。如果找不到该键,则它返回NOT_FOUND 。如果键不是数字,则返回CLIENT_ERROR不能递增或递减非数值。否则,将返回ERROR 。
Memcached incr命令的基本语法如下所示-
incr key increment_value
在此示例中,我们将访问者用作键并将其初始设置为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
Memcached decr命令的基本语法如下所示
decr key decrement_value
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
要增加或减少Memcached服务器中的数据,您需要分别使用Memcached incr或decr方法。
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"));
}
}
在编译和执行程序时,您将看到以下输出-
Connection to server successfully
set status:true
Get from Cache:5
Increment value:7
Decrement value:6
Get from Cache:6