实战Memcached缓存系统(5)Memcached的CAS程序实例

来源:互联网 发布:mysql批量导入数据 编辑:程序博客网 时间:2024/05/17 05:17

尊重知识,转载请注明本文来自:编程艺术家Poechant的CSDN博客 http://blog.csdn.net/poechant


1. 非CAS

首先看一个不是CAS的Memcached程序实例。实例的问题原型,见上一篇博文。

程序实例:

package com.sinosuperman.memcached;import java.io.IOException;import java.net.InetSocketAddress;import net.spy.memcached.MemcachedClient;public class Test {public static void main(String[] args) throws IOException {MemcachedClient cache = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));cache.set("x", 1800, "Love");String obj1 = (String) cache.get("x");String obj2 = (String) cache.get("x");obj2 = "Michael";cache.set("x", 1800, obj2);System.out.println("Non-CAS 2:\t" + obj2);System.out.println("Non-CAS 1:\t" + obj1);}}



运行结果:

2011-12-18 23:12:39.836 INFO net.spy.memcached.MemcachedConnection:  Added {QA sa=/127.0.0.1:11211, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0} to connect queue2011-12-18 23:12:39.843 INFO net.spy.memcached.MemcachedConnection:  Connection state changed for sun.nio.ch.SelectionKeyImpl@b09e89Non-CAS 2:MichaelNon-CAS 1:Love


可见在多个Client操作时,一定会引起写不一致性的问题。


2. CAS

程序实例:

package com.sinosuperman.memcached;import java.io.IOException;import java.net.InetSocketAddress;import net.spy.memcached.CASValue;import net.spy.memcached.MemcachedClient;public class Test {@SuppressWarnings("unchecked")public static void main(String[] args) throws IOException {MemcachedClient cache = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));cache.set("y", 1800, "Michael");CASValue casValue1 = cache.gets("y");CASValue casValue2 = cache.gets("y");cache.cas("y", casValue2.getCas(), "Love");System.out.println("CAS 2:\t" + casValue2.getCas());System.out.println("Value 2:\t" + casValue2.getValue());System.out.println("CAS 1:\t" + casValue1.getCas());System.out.println("Value 1:\t" + casValue1.getValue());}}

运行结果:

2011-12-18 23:07:14.528 INFO net.spy.memcached.MemcachedConnection:  Added {QA sa=/127.0.0.1:11211, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0} to connect queue2011-12-18 23:07:14.541 INFO net.spy.memcached.MemcachedConnection:  Connection state changed for sun.nio.ch.SelectionKeyImpl@1621e42CAS 2:11Value 2:LoveCAS 1:11Value 1:Love


原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 点我达装备抽查怎么办 空军常服大檐帽有一点变形怎么办 一般纳税人没有进项发票怎么办 汽车购买发票丢了怎么办 购买房子的发票丢了怎么办 购买的二手房发票丢失怎么办 购买空调时的发票丢失怎么办 发票购票本丢了怎么办 留学中介费贵了怎么办 车祸伤者不肯出院怎么办 增值税普通发票发票联丢失怎么办 纳税识别号错了怎么办 电子发票税号填写错误怎么办 发票抬头名称写错了怎么办 滴滴发票抬头写错了怎么办 普票抬头开错了怎么办 发票号码打错了怎么办 个人税票开错了怎么办 普票地址错了怎么办 专票税率开高了怎么办 专票税率开错了怎么办 发票姓名写错了怎么办 首付发票姓名写错怎么办 一般纳税人税率开错了怎么办 电子税票开错了怎么办 税率是6%开成3%怎么办 医院收费收错了怎么办 发票少打一个字怎么办 增值税发票抬头错了一个字怎么办 暂估入账跨年了怎么办 电子发票写错了怎么办 发票纳税人识别号写错了怎么办 电子发票忘填邮箱怎么办 公司名跟发票抬头不一样怎么办 买空调不给发票怎么办 卖苹果手机没有发票怎么办 刷机字库刷坏了怎么办 维棠不能播放视频怎么办 m3u8卡顿的厉害怎么办 下载了PDF不能用怎么办 pdf格式在电脑打不开怎么办