在AppEngine中安全地处理并发的Memcache更新

4
谷歌应用引擎文档中有关安全处理并发Memcache更新的说明: putIfUntouched和getIdentifiable方法可以用于提供一种安全地以原子方式更新Memcache键值对的方式,特别是当多个请求正在同时处理需要更新相同memcache键的情况时。(在这些情况下可能会出现竞争条件。)
我正在构建一个需要准确缓存值的应用程序,以下是我的代码,请帮忙检查是否正确:
        ...
        IdentifiableValue oldCountIdValue = mc.getIdentifiable( cacheKey );
        Long count = ( Long ) oldCountIdValue.getValue();
        if( count != null )
        {
            this.oldCountValue = oldCountIdValue;
            return count;
        }

        Long result = new Long( q.count() );
        mc.putIfUntouched( cacheKey, oldCountValue, result );
        return result;

我的问题是:如果putIfUntouched()返回false,代码应该返回什么?如何返回?
当数据存储添加一个实体时,我使用以下代码:
mc.increment( cacheKey, 1, initValue );

这个用法正确吗?

非常感谢。

1个回答

1

我需要了解一些关于你的代码的内容:
首先,为什么要检查 count != null?oldCountIdValue == null 不意味着 count == null 吗?反之亦然:如果 oldCountIdValue != null,那么 count != null

如果是这样的话,那么代码应该是:

IdentifiableValue oldCountIdValue = mc.getIdentifiable( cacheKey );
if (oldCountIdValue != null) {
   return ( Long ) oldCountIdValue.getValue();
}

Long result = new Long( q.count() );
mc.putIfUntouched( cacheKey, oldCountValue, result );
return result;

如果putIfUntouched返回null,这意味着您的结果变量不再准确,您可以执行以下操作:忽略并返回当前结果或从缓存中加载结果。

谢谢Shay,现在我想我明白了putIfUntouched()的工作原理。 - Mike

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接