Memcached, Locking and Race Conditions

前端 未结 4 1173
心在旅途
心在旅途 2021-02-02 13:14

We are trying to update memcached objects when we write to the database to avoid having to read them from database after inserts/updates.

For our forum post object we ha

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-02 13:27

    We encountered this in our system. We modified get so

    • If the value is unset, it sets it with a flag ('g') and [8] second TTL, and returns false so the calling function generates it.
    • If the value is not flagged (!== 'g') then unserialize and return it.
    • If the value is flagged (==='g') then wait 1 second and try again until it's not flagged. It will eventually be set by the other process, or expired by the TTL.

    Our database load dropped by a factor of 100 when we implemented this.

    function get($key) {
      $value=$m->get($key);
      if ($value===false) $m->set($key, 'g', $ttl=8);
      else while ($value==='g') {
        sleep(1);
        $value=$m->get($key);
      }
      return $value;
    }
    

提交回复
热议问题