memcached可以用于锁定吗? [英] Can memcached be used for locking?

查看:90
本文介绍了memcached可以用于锁定吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

memcached可用于缓存静态数据,从而减少数据库查找,并且通常执行memcached.get(id)memcached.set(id).

memcached can be used for a caching static data which reduces database lookup and typically does memcached.get(id) and memcached.set(id).

将其用于锁定机制可以吗? memcache.setmemcached.get是否总是提供数据(如果存在),或者如果请求花费太多时间,它只会返回None?

However is it fine to use this for locking mechanisms? Does memcache.set and memcached.get always give the data if it is present or will it just return None if the request is taking too much time?

我想避免同时访问由id标识的特定资源,并且我使用以下逻辑:

I want to avoid concurrent access to a particular resource identified by a id and I use this logic:

def access(id):
    if memcache.get(id):
        return access
    else:
        memcache.set(id)
        return true

如果有任何用户尝试访问该资源,则如果memcache.get(id) = username返回一个值,我们将拒绝访问,否则我们将执行memcache.set(id) = username来停止后续访问并允许当前用户访问.

If any user tries to access that resource, if memcache.get(id) = username returns a value we decline the access else we do memcache.set(id) = username to stop subsequent access and allow access for the current user.

像这样使用memcached可以吗? setget会实际提供数据(如果可用),而不管它花费的时间如何,或者会在最短的时间内从我发现的结果中给出最佳结果(例如:

Is it fine to using memcached like this? Will set and get actually give the data if its available regardless of the time it takes or does it give best possible result in the least possible time from whatever I have found (for example: Guaranteed memcached lock) so far is of the former category and might not work for locking thought it might work 99% of the time.

任何人都可以澄清以及是否有其他锁定机制?

Can anyone clarify and if there are alternative locking mechanisms?

推荐答案

对于任何对此感兴趣的人,我都在Memcache Github上的

For anyone intersted in this, I have created a thread on Memcache Github at Will memcached work reliably for implementing a locking mechanism?. It explains some of the common caveats using get and set and how to avoid that using add. Some blogs also explain this problem if you can search for distributed locking using memcache on your favorite search engine.

还有一个相关问题 Memcached,锁定和竞争条件可能会有所帮助关于如何更清楚地了解内存缓存的竞争条件.

There is also a related question Memcached, Locking and Race Conditions which might help on getting more clarity on memcache race conditions.

在Memcache论坛上有更多关于此的讨论:

Here is more discussions on this at the Memcache Forum:

线程1 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆