欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > thinkphp6 redis 哈希存储方式以及操作函数(笔记)

thinkphp6 redis 哈希存储方式以及操作函数(笔记)

2025/2/25 9:56:59 来源:https://blog.csdn.net/qq_35748913/article/details/143338502  浏览:    关键词:thinkphp6 redis 哈希存储方式以及操作函数(笔记)

逻辑:如果redis里没有指定表数据就进行存储再输出,如果有就直接输出,代码优化后几万条数据从数据库入redis也是三四秒的时间,数据以json方式存储:key用于数据ID 跟数据库数据ID同步,value用于存储整个字段包括数据,这样数据多不会占用多余内存

$name参数是数据库表名,跟数据库表名是同步一样的,直接调用即可

/*** 缓存指定表全部数据* @Author Xven <270988107@qq.com>* @return [type]                  [description]*/
function redis_data($name) {$redis = Cache::store('redis');$data = [];// 尝试从 Redis 获取数据$lists = $redis->hGetAll($name . ':list');if (!empty($lists)) {// Redis 中有数据,直接解码并返回foreach ($lists as $key => $value) {$data[$key] = json_decode($value, true);}} else {// Redis 中没有数据,从数据库获取并写入 Redis$list = Db::name($name)->cursor();$encodedData = [];// 开始一个多重操作$redis->multi();foreach ($list as $item) {$encoded = json_encode($item, JSON_UNESCAPED_UNICODE);$redis->hSet($name . ':list', $item['id'], $encoded);$data[] = $item; // 直接将数据库查询结果添加到 $data 数组中}// 执行多重操作中的所有命令$redis->exec();}return $data;
}
/*** 查询指定ID单条数据* @Author Xven <270988107@qq.com>* @param  [type]                  $name [description]* @param  [type]                  $id   [description]* @return [type]                        [description]*/
function find_redis($name, $id) {$redis = Cache::store('redis');$info = $redis->hMget($name . ':list', [$id]);if (!empty($info)) {$info = json_decode($info[$id], true);return $info;} else {return '';}
}
/*** 指定ID数据重存更新* @Author Xven <270988107@qq.com>* @param  [type]                  $id   [description]* @param  [type]                  $name [description]* @return [type]                        [description]*/
function update_redis($name, $id, $field) {$redis = Cache::store('redis');$cursor = Db::name($name)->where('id', $id)->limit(1)->cursor();foreach ($cursor as $v) {if (!empty($v)) {$sela = $redis->hSet($field, $id, json_encode($v));if ($sela) {return true;} else {return false;}}}
}
/*** 指定ID数据重存更新* @Author Xven <270988107@qq.com>* @param  [type]                  $id   [description]* @param  [type]                  $name [description]* @return [type]                        [description]*/
function del_redis($field, $id) {$redis = Cache::store('redis');$info = $redis->hDel($field, $id);if ($info) {return true;} else {return false;}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词