Answer the question
In order to leave comments, you need to log in
How to identify unique Memcached keys?
Hello!
I'm learning Memcached and, it seems, everything is working out so far. But the question arose, how to identify unique keys?
Well, for example, I have a database query that returns the number of attempts by a specific user:
if (class_exists('Memcached')) {
$ttl = 3600;
$cache = new Memcached();
$cache->addServer("127.0.0.1", 11211);
if(($cache->get('num_att')) != null) {
$total_count = $cache->get('num_att');
} else {
$sql = "SELECT * FROM sub_all WHERE user_id IN (?)";
if ($query = $db->prepare($sql)) {
$query->bind_param("i", $id);
$query->execute();
$result = $query->get_result();
$exist = $result->num_rows;
$total_count = $result->fetch_array();
$cache->set('num_att', $total_count, $ttl);
} else {
$errBox = 'Ошибка. Пожалуйста, повторите попытку.';
$stop_error = true;
}
}
}else {
die("Ошибка при подключении к кеш-серверу");
}
Answer the question
In order to leave comments, you need to log in
You have an id, you can include it in the name of the key. for example "num_att_$id"
. And in the same way, when saving the number of attempts to use the same key. There is no need to store anything else.
Keys can be deleted by prefix if you need to clear this cache. There is no direct functionality for this in memcached, but there are workarounds.
By the way, you don't need to check the cache and throw an error. The code should work without it. Moreover, the error message is clearly incorrect - the presence of the module is checked, and not the connection. =) You just need to correctly wrap the cache access with a check.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question