How can Memcached optimize DB queries?

class UserService:
  def getUser(self, user_id):
    key = "user::%s" % user_id //hash them
    user = cache.get(key) //try to get user from cache
    if user:
      return user
    user = database.get(user_id) //regain the user from our real db
    cache.set(key, user) //update cache
    return user

but in the meantime, there are many parts that we should cared about:
let’s take a close look at the code above, why do they written in such an order? can I change some of that order?
like: cache.set(key, user) and then database.set(user) //when we need to add some user to the db(and this user has higher possibilities that will be retrived later because it is newly added), so we store them to cache and our db. but if when we want to set user to db, db failed, then it will cause the data from cache and db different.
cache.delete(key) database.set(user) if db failed in the mid way, error won’t happened.

so the previous two example shows that any part in codes like this might have gone wrong, and the damage caused by that is the info in cache and db might be difference

posted @ 2020-10-20 02:30  EvanMeetTheWorld  阅读(18)  评论(0)    收藏  举报