Check if a key exists in Memcache

前端 未结 11 2348
无人共我
无人共我 2021-02-12 15:17

How do I check in PHP if a value is stored in Memcache without fetching it? I don\'t like fetching it because the values I have set are all 1MB in size and after I fetch it, I h

11条回答
  •  南旧
    南旧 (楼主)
    2021-02-12 15:45

    memcached now has the cas command. you can use it with a cas unique as 0 to get the EXISTS or NOT_FOUND responses:

    $ telnet localhost 11211
    Trying 127.0.0.1...
    Connected to localhost.
    Escape character is '^]'.
    set hello 0 0 5
    12345
    STORED
    gets hello
    VALUE hello 0 5 6743
    12345
    END
    cas hello 0 0 0 0
    
    EXISTS
    cas foo 0 0 0 0 
    
    NOT_FOUND
    

    In the transcript above, I first use the set command to set a key hello with value 12345. Then gets it back, which also returned a cas unique 6743. Then I try to use cas command to replace the value with nothing, but because the cas unique I used is 0, I got back EXISTS error.

    Finally I try to use cas to set a key foo that doesn't exist and get back NOT_FOUND error.

    Because memcached uses a global incrementing value for cas unique, using 0 is safe that it's not valid for the item you are trying to set and you would get back EXISTS error if it does exist.

    Sorry, not familiar with php's memcache client to put it in php code.

提交回复
热议问题