gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 11:23:44 28 4
gpt4 key购买 nike

我正在尝试使用 php 将数组附加到 redis 中的现有键。

我现在正在做的是尝试先获取 key 中的数组。如果键不存在,则将二维数组设置为该键。

如果键确实存在,则获取该键中的原始数组,然后将数组附加到原始数组。然后把它放回那把 key 。

我的问题是,当两个不同的客户端 A 和 B 同时添加新数组时,一些数组丢失了。

我的猜测是客户 A 和 B 得到相同的原始数组,但 A 先把它放回去。然后B放回去,覆盖Client A刚刚设置的记录。

我的代码是:

$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);

我应该怎么做才能做到这一点?

编辑:

这是日志

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

最佳答案

我解决了这个问题。原来我用错了数据结构,我应该用List。并使用 Lpush 和 Lpop 方法。

当客户端插入数据时,只需将数据插入列表即可。无需获取原始数据和新数据拼接。

关于php - 使用php将数组附加到redis中的现有键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55294193/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com