2010-02-19 83 views
16

目前我的应用程序缓存模型在内存缓存是这样的:执行AppEngine模型Memcaching的最佳方式是什么?

memcache.set("somekey", aModel) 

但尼克斯后在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() 
+0

我刚刚尝试过真正大型和复杂的模型,但结果大致相同。 – 2010-02-19 21:36:34

+0

也许GAE上有http://docs.python.org/library/timeit.html?这应该显示更准确的结果,但仍然 - 在阅读您链接到的博客条目后,我会预期protobuffers的性能与pickle之间的数量级差异 - 并且这应该由time.time()无论如何赶上。 – 2010-02-21 23:34:36

+0

我是使用java appengine,所以我懒得测试这个理论 - pickle()在某个地方缓存幕后结果,而to_protobuf不是?基于这篇文章,我不确定我会期望速度会有一个完整的数量级增长,因为即使使用protobuf版本,pickle仍然被称为。尽管如此,使用的空间肯定会大大缩小。 – 2010-02-22 02:45:28

回答

4

内存缓存调用仍然泡菜物体使用或不使用protobuf的。味酸是具有protobuf的对象,因为它具有非常简单的模型

平原泡菜对象比的protobuf +咸菜对象更大更快,因此,它们节省内存缓存时间,但是有更多的处理器时间在做protobuf的转换

因此,一般来说,任何方法都可以解决大致相同的问题......但是

您应该使用protobuf的原因是它可以处理模型版本之间的变化,而Pickle会出错。这个问题有一天会咬你,所以最好尽快处理它

+1

尽管提出了一些优点,但并非所有内容都是真实的。如果您查看代码,memcache api只会腌制非字符串。因此,使用protobuffed模型的列表将被酸洗,而不是单个模型。实际上protobufs的输出更简单和更小,我的测试表明它不是cpu密集型的 - 因此是最初的问题。模型版本点是有效的,但对我来说不是太重要,因为无论如何,您应该有一种处理无效缓存结果的方法,并且它不会经常发生。 – 2010-03-02 21:01:19

1

在App Engine中,pickle和protobufs都很慢,因为它们是用纯Python实现的。我发现使用str.join之类的方法编写我自己的简单序列化代码往往会更快,因为大部分工作都是在C中完成的。但这只适用于简单的数据类型。

+0

你是否也为模型对象做过这个工作?我会很好奇看到你的实施。 – 2010-03-15 11:00:28

+0

我曾经这样做,但python2.7给了我们cpickle,它现在更快。 – FoxyLad 2012-08-16 00:23:07

1

更快地做到这一点的一种方法是将模型转换为字典并使用本地eval/repr函数作为您的(de)序列化器 - 当然,一如既往的使用邪恶eval,但它应该因为没有外部步骤,所以在这里是安全的。

下面是一个类Fake_entity实例的实例。 您首先通过fake = Fake_entity(entity)创建您的字典,然后您可以简单地通过memcache.set(key, fake.serialize())存储您的数据。 serialize()是对repr的本地字典方法的简单调用,如果需要,还可以添加一些内容(例如在字符串的开头添加标识符)。

要取回它,只需使用fake = Fake_entity(memcache.get(key))即可。 Fake_entity对象是一个简单的字典,其键也可以作为属性访问。你可以正常访问你的实体属性,除了referenceProperties提供的键而不是提取对象(这实际上非常有用)。你也可以通过fake.get()或者更多的方式获取()实际的实体,改变它然后用fake.put()保存。

它不适用于列表(如果您从查询中获取多个实体),但可以通过使用像'### FAKE MODEL ENTITY ###'这样的标识符作为分隔符的连接/拆分函数轻松进行调整。只与db.Model一起使用,需要对Expando进行小的调整。

class Fake_entity(dict): 
    def __init__(self, record): 
     # simple case: a string, we eval it to rebuild our fake entity 
     if isinstance(record, basestring): 
      import datetime # <----- put all relevant eval imports here 
      from google.appengine.api import datastore_types 
      self.update(eval(record)) # careful with external sources, eval is evil 
      return None 

     # serious case: we build the instance from the actual entity 
     for prop_name, prop_ref in record.__class__.properties().items(): 
      self[prop_name] = prop_ref.get_value_for_datastore(record) # to avoid fetching entities 
     self['_cls'] = record.__class__.__module__ + '.' + record.__class__.__name__ 
     try: 
      self['key'] = str(record.key()) 
     except Exception: # the key may not exist if the entity has not been stored 
      pass 

    def __getattr__(self, k): 
     return self[k] 

    def __setattr__(self, k, v): 
     self[k] = v 

    def key(self): 
     from google.appengine.ext import db 
     return db.Key(self['key']) 

    def get(self): 
     from google.appengine.ext import db 
     return db.get(self['key']) 

    def put(self): 
     _cls = self.pop('_cls') # gets and removes the class name form the passed arguments 
     # import xxxxxxx ---> put your model imports here if necessary 
     Cls = eval(_cls) # make sure that your models declarations are in the scope here 
     real_entity = Cls(**self) # creates the entity 
     real_entity.put() # self explanatory 
     self['_cls'] = _cls # puts back the class name afterwards 
     return real_entity 

    def serialize(self): 
     return '### FAKE MODEL ENTITY ###\n' + repr(self) 
     # or simply repr, but I use the initial identifier to test and eval directly when getting from memcache 

我欢迎这个速度测试中,我会以为这是一个相当比其他方式更快。此外,如果您的模型在此期间发生了某种变化,则不会有任何风险。

下面是一个序列化假实体的例子。采取在日期时间(创建)一个特定的外观以及参考属性(子域):

### FAKE模型实体###
{ '状态':u'admin', 'session_expiry':无,' first_name':u'Louis','last_name':u'Le Sieur','modified_by':None,'password_hash':u'a9993e364706816aba3e25717000000000000000','language':u'fr','created':datetime.datetime ','modified':None,'created_by':None,'email':u' [email protected]','key':'agdqZXJlZ2xlcgwLEgVMb2dpbhjmAQw','session_ref ':None,'_cls':'models.Login','groups':[],'email___password_hash':u' [email protected]+a9993e364706816aba3e25717000000000000000','subdomain':datastore_types.Key.from_path(u'Subdomain' ,229L,_app = u'jeregle'),'allowed':[],'permissions':[]}


就我个人而言,我也使用静态变量(比memcache更快)在短期内缓存我的实体,并在服务器发生更改或由于某种原因刷新其内存时获取数据存储(事实上经常发生这种情况) 。

相关问题