2

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
2
  • Hard to know with nothing to work with. Include the array you loop and what you expect out from the code. Commented Mar 22, 2019 at 6:55
  • I just paste my log.hope that make sense Commented Mar 22, 2019 at 7:08

1 Answer 1

3

I slove this problem. Turns out I use the wrong data structure, I should use List. And use Lpush and Lpop method.

when Client insert data, just push data into a list. no need to get original data and splice with new data.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.