2016-11-08 2 views
0

매우 비슷한 질문이 게시되어 답변되었습니다. 그러나 지금까지 발견 한 모든 솔루션은 Memcache이 아닌 PHP Memcached extension을 사용하고 있습니다. 미리 정의 된 키로 시작하는 모든 memcache 항목을 삭제하거나 만료하려고합니다. 예 : so_something, so_something_else .... 어떤 도움이라도 대단히 감사합니다.PHP memcache 확장을 사용하여 memcached에서 같은 접두사 키를 가진 항목을 삭제하는 방법은 무엇입니까?

답변

0

일부 연구 끝에 표준 Memcache 명령을 사용하여 조사하는 방법을 생각했습니다. 하지만 불행히도 memcache 서버로 이동하여주의해서 사용해야합니다. 제 경우에는 배포 후에 만 ​​사용됩니다 :

/** 
* Helper function to expire memcache entries with a specific key prefix. 
* 
* @param string $key_prefix 
* The memcache key prefix. 
* @param array $servers 
* Array of used memcache servers. 
* @return array 
* 
*/ 
function memcache_delete_by_key($key_prefix = '', $servers = array()) { 
    $mc = new Memcache(); 
    $delete_keys = array(); 
    foreach ($servers as $server => $default) { 
    list($host, $port) = explode(':', $server); 
    $mc->addServer($host, $port); 
    // Extract all the keys from Memcache. 
    $stats = memcache_command($server, $port, "stats items"); 
    $stat_lines = explode("\r\n", $stats); 
    $slabs = array(); 
    $keys = array(); 
    foreach ($stat_lines as $line) { 
     if (preg_match("/STAT items:([\d]+):number ([\d]+)/", $line, $matches)) { 
     if (isset($matches[1]) && !in_array($matches[1], $slabs)) { 
      $slabs[] = $matches[1]; 
      $string = memcache_command($server, $port, "stats cachedump " . $matches[1] . " " . $matches[2]); 
      preg_match_all("/ITEM (.*?) /", $string, $matches); 
      $keys[] = $matches[1]; 
     } 
     } 
    } 
    $delete_keys = call_user_func_array('array_merge', $keys); 
    // Locate all keys that begin with our prefix. 
    foreach ($delete_keys as $index => $key) { 
     // If strpos returns 0 (not false) then we have a match. 
     if (strpos($key, $key_prefix) === 0) { 
     $mc->delete($key); 
     } 
    } 
    } 

    return $delete_keys; 
} 

/* 
* Helper function to send memcache commands to a given Memcache Server 
*/ 
function memcache_command($server, $port, $command) { 
    $s = @fsockopen($server, $port); 
    if (!$s) { 
    return die("Cant connect to:" . $server . ":" . $port); 
    } 
    fwrite($s, $command . "\r\n"); 
    $buf = ""; 
    while ((!feof($s))) { 
    $buf .= fgets($s, 256); 
    // Stat says 'END'. 
    if (strpos($buf, "END\r\n") !== FALSE) { 
     break; 
    } 
    // Delete says DELETED or NOT_FOUND. 
    if (strpos($buf, "DELETED\r\n") !== FALSE || strpos($buf, "NOT_FOUND\r\n") !== FALSE) { 
     break; 
    } 
    // Flush_all says ok. 
    if (strpos($buf, "OK\r\n") !== FALSE) { 
     break; 
    } 
    } 
    fclose($s); 
    return ($buf); 
}