I'm trying to append an array to an existing key in redis using php.
What I'm doing now is trying to get the array in the key first. If the key does not exist, then set an Two-dimensional array to that key.
If the key does exist, get the original array in that key, then append an array to the original array. Then put it back to that key.
My problem is that, when two different clients A AND B append new array at the same time, some array is missing.
My guess is that clients A AND B get same original array, but A puts it back first. Then B puts it back after, overwrite the record Client A just set.
My code is:
$cache = new Redis();
$origin = $cache->getArray(self::CACHE_PREFIX . $uid);
if(is_array($origin) && count($origin) > 0){
array_push($origin, $arr);
$master = $origin;
}else{
$master = [$arr];
}
$cache->setArray(self::CACHE_PREFIX . $uid, $master);
What should I do to make this right?
EDIT:
here is the log
2019-03-22 11:57:45 1553227065.3247 ORIGINfalse //Client A operate, the key is not exist
2019-03-22 11:57:45 1553227065.326 MASTER[{"sids":["759"],"to":"7223","status":1,"type":"notice"}] //Client A insert an new array
2019-03-22 11:57:45 1553227065.3402 ORIGIN[{"sids":["759"],"to":"7223","status":1,"type":"notice"}] //Client A operate
2019-03-22 11:57:45 1553227065.3402 ORIGIN[{"sids":["759"],"to":"7223","status":1,"type":"notice"}] //Client B operate
2019-03-22 11:57:45 1553227065.3411 MASTER[{"sids":["759"],"to":"7223","status":1,"type":"notice"},{"sids":["764"],"to":"7223","status":1,"type":"notice"}] //Client A append an new array
2019-03-22 11:57:45 1553227065.3413 MASTER[{"sids":["759"],"to":"7223","status":1,"type":"notice"},{"sids":["760"],"to":"7223","status":1,"type":"notice"}] //Client B also append an new array ,and overwrite Client A's data