Memcached best practices - small objects and lots of keys or big objects and few keys?

前端 未结 6 1707
梦谈多话
梦谈多话 2021-02-02 11:23

I use memcached to store the integer result of a complex calculation. I\'ve got hundreds of integer objects that I could cache! Should I cache them under a single key in a more

相关标签:
6条回答
  • 2021-02-02 11:27

    I would say you should store values individually and use some kind of helper class to retrieve values with multiget and generate a complex dataobject for you.

    0 讨论(0)
  • 2021-02-02 11:30

    It depends on what are those numbers. If you could, for example, group them in ranges, then you could optimize the storage. If you could hash them, into a map, or hashtable and store that map serialized in memcached would be good to.

    Anyway, you can save many little keys, just make sure you configure the slabs to have chunks with small size, so you will not waste memory space.

    0 讨论(0)
  • 2021-02-02 11:37

    The less processing you have to do of the cached values, the better. So why not just dump them into the cache individually?

    0 讨论(0)
  • 2021-02-02 11:38

    I would say lots of little keys. This way you can get the exact result you want in 1 call with minimal serialization effort.

    If you store it in another object (an array for example) you will have to fetch the array from cache and then fetch the item you actually want again from that array, plus you have the overhead of serializing/deserializing the whole complex object again. Depending on your language of choice this might mean manually writing a serialization/deserialization function from scratch.

    0 讨论(0)
  • 2021-02-02 11:44

    I wrote somewhat large analysis at http://dammit.lt/2008/12/25/memcached-for-small-objects/ - it outlines how to optimize memcached for small object storage - it may shed quite some light on the issue.

    0 讨论(0)
  • 2021-02-02 11:53

    It depends on your application. While memcached is very fast, it does require some request transmission and memory lookup time per request. Those numbers increase depending on whether or not the server is on the local machine (localhost), on the local network, or across a wide area. The size of your cache generally doesn't affect the lookup speed.

    So, if your application is using MANY objects per processing unit (per request, method, or what-have-you), then it's generally better to define your cache in a way which lowers total number of hits to the cache while at the same time trying not to duplicate cache data. Like everything else, it's a balance.

    i.e. If you have a web request which pulls a list of blog posts, it would be more beneficial to cache the entire object list as one memcached key, rather than (and this is a somewhat bad example, obviously) caching an array of cache keys for that list, which relate to individually memcached objects.

    0 讨论(0)
提交回复
热议问题