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

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

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

php 复制代码
/**
 * 缓存指定表全部数据
 * @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;
}
php 复制代码
/**
 * 查询指定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 '';
	}
}
php 复制代码
/**
 * 指定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;
			}
		}
	}
}
php 复制代码
/**
 * 指定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;
	}
}
相关推荐
damoluomu4 天前
挑 PHP CMS 之前,先学会看它的协议
php
IT大白鼠4 天前
Redis 系列 · 第 01 篇——认知入门:Redis 是什么
redis·nosql
彧azz4 天前
Linux 环境下 Redis 学习总结:数据类型、持久化、锁、事务、主从与缓存问题
linux·redis·笔记·学习·面试
another heaven4 天前
【算法/C++ MD5算法能否逆解码?原理、C++实现与同类哈希算法对比】
c++·算法·哈希算法
lbb 小魔仙4 天前
OpenClaw + cpolar 实战:远程 NAS、分享小游戏、RDP,再配置公网 AI 入口
数据库·人工智能·redis·oracle·prometheus
夕除4 天前
redis--018
redis
两锭子4 天前
Redis基础
redis
烟沙九洲4 天前
Redis 缓存穿透、缓存击穿、缓存雪崩
数据库·redis
字节探索4 天前
Redis 只会当缓存用?这 10 大实战场景,让你的系统快到飞起
redis·后端
子非鱼a4 天前
【WEB】Online ToolWEB
php