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;
	}
}
相关推荐
从零开始的ops生活4 小时前
【Day 80】Linux-NAS 和 SAN 存储
linux·运维·php
shizhenshide4 小时前
为什么有时候 reCAPTCHA 通过率偏低,常见原因有哪些
开发语言·php·验证码·captcha·recaptcha·ezcaptcha
21号 16 小时前
9.Redis 集群(重在理解)
数据库·redis·算法
爬山算法6 小时前
Redis(73)如何处理Redis分布式锁的死锁问题?
数据库·redis·分布式
jason.zeng@15022076 小时前
centos中安装redis
linux·redis·centos
祈祷苍天赐我java之术8 小时前
Redis 数据类型与使用场景
java·开发语言·前端·redis·分布式·spring·bootstrap
哥哥还在IT中14 小时前
Redis多线程架构深度解析-从单线程到I/O Threading
redis·架构·bootstrap
元闰子15 小时前
怎么让程序更高效地连起来?
数据库·redis·mysql
洲覆15 小时前
Redis 内存淘汰策略
开发语言·数据库·redis·缓存
偶尔贪玩的骑士15 小时前
Kioptrix Level 1渗透测试
linux·开发语言·网络安全·php