1

使用 Google App Engine NDB,memcache 的大部分方面都是自动处理的。但是,一个项目在被读取至少一次之前不会在 Memcache 中可用。所以首先必须使用 get 读取项目,然后 memcache 存储它。Put() 将其从内存缓存中删除。

但是,我需要在放置时立即在 memcache 中可用。我是 memcache 的新手,所以我不完全确定幕后的一切是如何运作的,但有两种方法可以做到这一点:

  1. 在实体的 put() 之后,立即执行 get(),以便它在 memcache 中可用。
  2. 在 put() 之后,立即手动设置 memcache 中的项目。这是有道理的,但我不确定这种方法是否有任何问题。如果我在 memcache 中手动设置某些内容,这会干扰 NDB 的其余自动 memcache 处理吗? 另外,在手动设置 memcache 中的内容时我应该使用什么键,以便在获取时,自动 memcache 处理程序知道要查找什么?
4

1 回答 1

1

I suspect you are referring to this:

Memcache does not support transactions. Thus, an update meant to be applied to both the Datastore and memcache might be made to only one of the two. To maintain consistency in such cases (possibly at the expense of performance), the updated entity is deleted from memcache and then written to the Datastore. A subsequent read operation will find the entity missing from memcache, retrieve it from the Datastore, and then update it in memcache as a side effect of the read. Also, NDB reads inside transactions ignore the Memcache.

So if you need something to be available on put then you'll have to cache it in memcache yourself.

Which brings us to 2)

If you manually set something in memcache AFAIK it won't interact with NDB's automatic caching in any way. Also AFAIK you can't set a manual memcache entry with a key that the automatic version will then be able to automatically work with.

You simply have to build a layer of memcache around your content that you explicitly control. Every time you to do a put you use a function that puts to the datastore then into memcache, invalidating existing entries if required. Likewise for get, you try memcache first then fall back to the datastore. Which sounds almost exactly like what NDB is doing already for you!

Perhaps look at the Policy functions options for finer control: https://developers.google.com/appengine/docs/python/ndb/cache#policy_functions

Don't forget however that the in context cache might well be doing what you want already:

The in-context cache persists only for the duration of a single incoming HTTP request and is "visible" only to the code that handles that request. It's fast; this cache lives in memory. When an NDB function writes to the Datastore, it also writes to the in-context cache. When an NDB function reads an entity, it checks the in-context cache first. If the entity is found there, no Datastore interaction takes place.

Queries do not look up values in any cache. However, query results are written back to the in-context cache if the cache policy says so (but never to Memcache).

So if your put and subsequent get is happening in the same request it's coming out of the in-context cache in any case.

于 2012-11-05T11:07:41.980 回答