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.

    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向