dsaaqdz6223 2019-03-22 06:42
浏览 62

使用php将数组附加到redis中的现有键

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
  • 写回答

1条回答 默认 最新

  • dongzhao1930 2019-03-22 08:52
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 Excel发现不可读取的内容
  • ¥15 UE5#if WITH_EDITOR导致打包的功能不可用
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。