memcache CAS实现原子操作

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/guyeliuxiahui/article/details/48629069

背景: 多个分布式系统实现计数器累加。 

 

protected Boolean execute() throws Exception {
        String memcachedKey = "testCAS";
        Boolean exist = true;
        try {
            exist = memcachedService.add(memcachedKey, 1 ,60000);
            if (exist) {
                exist = false;
            } else {
                exist = checkExecuteOver(memcachedKey);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return exist;
}

    public Boolean checkExecuteOver(String memcachedKey) throws Exception {
        MemcachedItem memcachedItem = memcachedService.gets(memcachedKey);
        Boolean exist;
        long casUnique = memcachedItem.getCasUnique();
        int value = (int) memcachedItem.getValue();
        if (value >= (distributed.getAllNumberList().size() - 1)) {
            exist = true;
        } else {
            boolean unanimous = memcachedService.cas(memcachedKey, value + 1 ,casUnique);
            if (unanimous) {
                exist = false;
            } else {
                // 版本号不一致 重新计算
                exist = checkExecuteOver(memcachedKey);
            }
        }
        return exist;
}

展开阅读全文

没有更多推荐了,返回首页