memcache CAS实现原子操作

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

 

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;
}

你可能感兴趣的:(缓存)