AppEngine Model Memcaching的最佳方法是什么?

Koe*_*Bok 16 google-app-engine memcached google-cloud-datastore

目前我的应用程序在memcache中缓存模型,如下所示:

memcache.set("somekey", aModel)
Run Code Online (Sandbox Code Playgroud)

但尼克斯在http://blog.notdot.net/2009/9/Efficient-model-memcaching上的帖子表明,首先将其转换为protobuffers效率要高得多.但经过一些测试后,我发现它的尺寸确实较小,但实际上较慢(约10%).

其他人有相同的经历,还是我做错了什么?

测试结果:http://1.latest.sofatest.appspot.com/?times = 1000

import pickle
import time
import uuid

from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import util
from google.appengine.datastore import entity_pb
from google.appengine.api import memcache

class Person(db.Model):
 name = db.StringProperty()

times = 10000

class MainHandler(webapp.RequestHandler):

 def get(self):

  self.response.headers['Content-Type'] = 'text/plain'

  m = Person(name='Koen Bok')

  t1 = time.time()

  for i in xrange(int(self.request.get('times', 1))):
   key = uuid.uuid4().hex
   memcache.set(key, m)
   r = memcache.get(key)

  self.response.out.write('Pickle took: %.2f' % (time.time() - t1))


  t1 = time.time()

  for i in xrange(int(self.request.get('times', 1))):
   key = uuid.uuid4().hex
   memcache.set(key, db.model_to_protobuf(m).Encode())
   r = db.model_from_protobuf(entity_pb.EntityProto(memcache.get(key)))


  self.response.out.write('Proto took: %.2f' % (time.time() - t1))


def main():
 application = webapp.WSGIApplication([('/', MainHandler)], debug=True)
 util.run_wsgi_app(application)


if __name__ == '__main__':
 main()
Run Code Online (Sandbox Code Playgroud)

TFD*_*TFD 4

Memcache 调用仍然会使用或不使用 protobuf 来腌制对象。Pickle 使用 protobuf 对象更快,因为它有一个非常简单的模型

普通 pickle 对象比 protobuf+pickle 对象大,因此它们节省 Memcache 上的时间,但进行 protobuf 转换需要更多的处理器时间

因此,一般来说,两种方法的效果都差不多……但是

您应该使用 protobuf 的原因是它可以处理模型版本之间的更改,而 Pickle 会出错。这个问题总有一天会困扰你,所以最好早点解决它