转载

Memcached递增递减数据

   

Memcached的incr 和 decr命令用于增加现有键的数值递减。如果键未找到或如果关键的不是数字,则返回NOT_FOUND。那么CLIENT_ERROR不能增加或返回递减非数值错误。

Incr

语法

memcached的incr命令的基本语法如下所示:

 incr key increment_value

示例

 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

在上面的例子中,我们已经使用visitors为一个键,并设置10为初始值,之后为visitors增量5。

Decr

语法

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

使用Java应用程序递增递减数据

要在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
   
正文到此结束
Loading...