thinkphp6.0封装数据库及缓存模型
项目中的thinkphp6.0\app\common\Model.php
1 <?php
2 /**
3 * 数据库及缓存模型
4 */
5 namespace app\common;
6
7 use app\index\server\RedisServer;
8 use think\db\BaseQuery;
9 use think\facade\Db;
10 use think\facade\Log;
11
12 class Model
13 {
14 protected $name;
15
16 /** 查询多条数据信息(批量查询方法), 缓存中未找到时去数据库查询
17 * @param $ids
18 * @return array
19 */
20 public function getCacheList($ids)
21 {
22 // 整理查询的数据, 并存入 $key
23 $keys = [];
24 foreach ($ids as $id) {
25 if($id)
26 {
27 $keys[$id] = $id;
28 }
29 }
30 if (empty($keys)) {
31 return [];
32 }
33
34 // 准备结果集
35 $result = [];
36
37
38 /** 在Redis中查询数据
39 * @var \Redis $redis
40 */
41 $redis = Instance::getInstance(RedisServer::class);
42 if ($redis) {
43 //创建管道,批量获取
44 $pip = $redis->pipeline();
45 foreach ($keys as $id) {
46 $pip->hGetAll(static::class . ':' . $id);
47 }
48 if ($caches = $pip->exec()) {
49 foreach ($caches as $value) {
50 if ($value) {
51 // 在$key中删除掉已查询到的数据
52 unset($keys[$value['id']]);
53 $result[$value['id']] = $value;
54 }
55 }
56 }
57 }
58
59 // 如果 $keys 不为空, 则表示有数据未从缓存中查询到, 在 mysql 中进行查询并缓存到Redis
60 if ($keys) {
61 foreach ($this->query()->whereIn('id', array_values($keys))->cursor() as $item) {
62 $redis->hMSet(static::class . ':' . $item['id'], $item);
63 $redis->expire(static::class . ':' . $item['id'], 60); //有效期10分钟
64 $result[$item['id']] = $item;
65 }
66 }
67 return $result;
68 }
69
70
71 /** 查询单条数据信息, 缓存中未找到时去数据库查询
72 * @param $id
73 * @param null $showKey
74 * @return mixed|null
75 */
76 public function getCacheInfo($id, $showKey = null)
77 {
78 $redis = Instance::getInstance(RedisServer::class);
79 if ($redis) {
80 if ($cache = $redis->hGetAll(static::class . ':' . $id)) {
81 return $showKey ? $cache[$showKey] : $cache;
82 }
83 }
84 $data = $this->query()->where('id', $id)->find();
85 if ($data) {
86 $redis->hMSet(static::class . ':' . $id, $data);
87 $redis->expire(static::class . ':' . $id, 60); //有效期10分钟
88 return $showKey ? $data[$showKey] : $data;
89 }
90 return null;
91 }
92
93
94 /** 查询多条数据信息, 缓存中未找到时去数据库查询
95 * @param $ids
96 * @return array
97 */
98 public function getCacheDataList($ids)
99 {
100 $result = [];
101 foreach ($ids as $id) {
102 $result[$id] = $this->getCacheInfo($id);
103 }
104 return $result;
105 }
106
107
108 /** 根据ID执行单条数据查询, 并存储到Redis
109 * @param $id
110 * @return null
111 */
112 public function setCacheInfo($id)
113 {
114 $redis = Instance::getInstance(RedisServer::class);
115 $data = $this->query()->where('id', $id)->find();
116 if ($data) {
117 $redis->hMSet(static::class . ':' . $id, $data);
118 $redis->expire(static::class . ':' . $id, 600); //有效期10分钟
119 return $data;
120 }
121 return null;
122 }
123
124
125
126 /** 数据库中根据ID查询信息(不经过缓存)
127 * @param $id
128 * @param string $field
129 * @return mixed
130 */
131 public function getById($id, $field = '*')
132 {
133 $where = [
134 'id' => $id,
135 'is_delete' => 0
136 ];
137 return $this->query()->where($where)->field($field)->find();
138 }
139
140
141
142 /** 数据库中根据ID查询用户信息(不经过缓存)
143 * @param $id
144 * @param string $field
145 * @return mixed
146 */
147 public function getByUserId($userId)
148 {
149 $where = [
150 'user_id' => $userId,
151 'is_delete' => 0
152 ];
153 return $this->query()->where($where)->find();
154 }
155
156 /**
157 * @return BaseQuery
158 */
159 public function query()
160 {
161 return Db::name($this->name);
162 }
163
164
165
166 /** 创建$query对象
167 * @return \think\Model
168 */
169 public static function createQuery($field = '*', $where = null, $order = null)
170 {
171 $query = Instance::getInstance(static::class)->query()->field($field);
172 if ($where) {
173 $query->where($where);
174 }
175 if ($order) {
176 $query->order($order);
177 }
178 return $query;
179 }
180
181
182 /** 创建查询$query 并添加查询条件, (where, order, limit, field)
183 * 不直接调用, 只通过该类下的 select等方法调用
184 * @param null $where
185 * @param array $order
186 * @param null $limit
187 * @param null $field
188 * @return BaseQuery
189 */
190 public function createSelect($where = null, $order = [], $limit = null, $field = null)
191 {
192 $query = $this->query();
193 if ($where) {
194 $query->where($where);
195 }
196 if ($field) {
197 $query->field($field);
198 }
199 if ($order) {
200 foreach ($order as $key => $value) {
201 $query->order($key, $value);
202 }
203 }
204 if ($limit) {
205 if (is_integer($limit)) {
206 $query->limit($limit);
207 } else {
208 $query->limit($limit[0], $limit[1]);
209 }
210 }
211 return $query;
212 }
213
214
215 /** 多条数据查询方法
216 * @param null $where
217 * @param array $order
218 * @param null $limit
219 * @param null $format
220 * @param null $field
221 * @return array
222 */
223 public function select($where = null, $order = [], $limit = null, $format = null, $field = null)
224 {
225 $result = [];
226 $query = $this->createSelect($where, $order, $limit, $field);
227 if ($dataList = $query->select()) {
228 foreach ($dataList as $value) {
229 $result[] = $format ? call_user_func_array($format, [$value]) : $value;
230 }
231 }
232 return $result;
233 }
234
235
236 /** 单条数据查询方法
237 * @param null $where
238 * @param array $order
239 * @param null $limit
240 * @param null $field
241 * @return mixed
242 */
243 public function find($where = null, $order = [], $limit = null, $field = null)
244 {
245 return $this->createSelect($where, $order, $limit, $field)->find();
246 }
247
248 public function selectIndex($where = null, $order = [], $limit = null, $format = null, $field = null)
249 {
250 $result = [];
251 $query = $this->createSelect($where, $order, $limit, $field);
252 if ($dataList = $query->select()) {
253 foreach ($dataList as $value) {
254 $result[$value['id']] = $format ? call_user_func_array($format, [$value]) : $value;
255 }
256 }
257 return $result;
258 }
259
260
261 /** 根据ID删除数据(软删除)
262 * @param $id
263 * @return mixed
264 */
265 public function deleteById($id)
266 {
267 return $this->query()->where(['id' => $id])->update(['is_delete' => 1]);
268 }
269
270
271 /** 根据where条件删除数据
272 * @param $where
273 * @return mixed
274 */
275 public function deleteByWhere($where)
276 {
277 return $this->query()->where($where)->delete();
278 }
279
280
281 /** 插入数据
282 * 自动条件创建时间和更新时间
283 * @param $data
284 * @param array $exception
285 * @return false
286 * @throws Exception
287 */
288 public function create($data, $exception = [])
289 {
290 try {
291 $data['create_time'] = time();
292 $data['update_time'] = time();
293 $id = $this->query()->insertGetId($data);
294
295 if ($id) {
296 $data['id'] = $id;
297 return $data;
298 } else {
299 return false;
300 }
301 } catch (\Exception $e) {
302 Log::record(Db::getLastSql(), 'SQL-ERROR');
303 Log::record($e->getMessage(), 'SQL-ERROR');
304 if ($exception) {
305 throw new Exception($exception);
306 }
307 return false;
308 }
309 }
310
311 /**
312 * 根据数组和key 获取ids
313 * @param array $arr
314 * @param null $key
315 * @return bool|string
316 */
317 public function getIds($arr = [], $key = null)
318 {
319 if (empty($arr) || empty($key)) {
320 return false;
321 }
322 $res = [];
323 foreach ($arr as $k => $v) {
324 $res[] = $v[$key];
325 }
326 $res = implode(',', $res);
327 return $res;
328 }
329
330
331 /** 更新数据信息
332 * 自动添加更新时间
333 * @param $where
334 * @param $data
335 * @param array $exception
336 * @return false
337 * @throws Exception
338 */
339 public function update($where, $data, $exception = [])
340 {
341 try {
342 if (!is_array($where)) {
343 $where = [
344 'id' => $where
345 ];
346 }
347 $data['update_time'] = time();
348 return $this->query()->where($where)->update($data);
349 } catch (\Exception $e) {
350 Log::record(Db::getLastSql(), 'SQL-ERROR');
351 Log::record($e->getMessage(), 'SQL-ERROR');
352 if ($exception) {
353 throw new Exception($exception);
354 }
355 return false;
356 }
357 }
358
359 }
thinkphp6.0封装数据库及缓存模型的更多相关文章
- iOS数据库离线缓存思路和网络层封装
一直想总结一下关于iOS的离线数据缓存的方面的问题,然后近期也简单的对AFN进行了再次封装.全部想把这两个结合起来写一下.数据展示型的页面做离线缓存能够有更好的用户体验,用户在离线环境下仍然能够获取一 ...
- ThinkPHP6.0在phpstorm添加查询构造器和模型的代码提示
ThinkPHP6.0升级后 使用查询构造器和模型都没有了提示 原因是tp6源码中没有添加注释 找到Model.php * @method Query where(mixed $field, stri ...
- 第六十二篇、AFN3.0封装网络请求框架,支持缓存
1.网络请求 第一种实现方式: 功能:GET POST 请求 缓存逻辑: 1.是否要刷新本地缓存,不需要就直接发起无缓存的网络请求,否则直接读取本地数据 2.需要刷新本地缓存,先读取本地数据,有就返回 ...
- Python之路,Day10 - 异步IO\数据库\队列\缓存
Python之路,Day9 - 异步IO\数据库\队列\缓存 本节内容 Gevent协程 Select\Poll\Epoll异步IO与事件驱动 Python连接Mysql数据库操作 RabbitM ...
- python面试题库——3数据库和缓存
第三部分 数据库和缓存(46题) 列举常见的关系型数据库和非关系型都有那些? 关系型数据库: Oracle.DB2.Microsoft SQL Server.Microsoft Access.MySQ ...
- 【原创】分布式之数据库和缓存双写一致性方案解析(三) 前端面试送命题(二)-callback,promise,generator,async-await JS的进阶技巧 前端面试送命题(一)-JS三座大山 Nodejs的运行原理-科普篇 优化设计提高sql类数据库的性能 简单理解token机制
[原创]分布式之数据库和缓存双写一致性方案解析(三) 正文 博主本来觉得,<分布式之数据库和缓存双写一致性方案解析>,一文已经十分清晰.然而这一两天,有人在微信上私聊我,觉得应该要采用 ...
- 异步IO/协程/数据库/队列/缓存(转)
原文:Python之路,Day9 - 异步IO\数据库\队列\缓存 作者:金角大王Alex add by zhj: 文章很长 引子 到目前为止,我们已经学了网络并发编程的2个套路, 多进程,多线程,这 ...
- 数据库与缓存:2.Redis数据库的基本知识
1.属于什么类型的数据库 not only sql 非关系型数据库,与传统的关系型数据库不同,存储形式都是kv形式. 2.特点 几乎不支持事务,key-value形式存储,支持队列和缓存(可以设置数 ...
- JavaScript实现TwoQueues缓存模型
本文所指TwoQueues缓存模型,是说数据在内存中的缓存模型. 无论何种语言,都可能需要把一部分数据放在内存中,避免重复运算.读取.最常见的场景就是JQuery选择器,有些Dom元素的选取是非常耗时 ...
- iOS超全开源框架、项目和学习资料汇总--数据库、缓存处理、图像浏览、摄像照相视频音频篇
iOS超全开源框架.项目和学习资料汇总--数据库.缓存处理.图像浏览.摄像照相视频音频篇 感谢:Ming_en_long 的分享 大神超赞的集合,http://www.jianshu.com/p/f3 ...
随机推荐
- 点亮PC13- 使用寄存器点亮
#include "stm32f10x.h" // Device header int main(void) { // 打卡GPIOC的时钟 RCC->APB2ENR = 0 ...
- filter 加 indexOf 方法去重数组
let arr = [1, 2, 3, 4, 3, 2, 3, 4, 6, 7, 6] let unique = (arr) => { console.log(arr) return arr.f ...
- Putty 远程 连接kali Linux拒绝访问 refused connection
1. 设置 ssh 文件 crtl + alt + t 代开终端 输入命令: vim /etc/ssh/sshd_config 说明 : 使用 vim 编辑器编辑 ssh 文件 : 说明: 修改第3 ...
- 如何在 ubuntu 上搭建 minio
由于腾讯的对象存储服务器(COS)的半年免费试用期已过,所以寻思鼓捣一下 minio,试着在自己的服务器上搭建一套开源的 minio 对象存储系统. 单机部署基本上有以下两种方式. 直接安装 最基础的 ...
- 一文了解 Conda(包教包会,不会留言)
Conda 使用指南 Conda 是一个开源包管理和环境管理系统,能够以跨平台的方式进行软件包的安装.管理和依赖管理,特别适用于 Python 和 R 语言的环境管理.本文整理了常见 Conda 命令 ...
- Machine Learning Week_1 Model and Cost Function 5-8
目录 2.5 Video: Cost Function Intuition-1 unfamiliar words 2.6 Reading: Cost Function Intuition-1 unfa ...
- ES检索服务搜索结果高亮
一.前言 在实际使用中搜索结果中的关键词前端通常会以特殊形式展示,比如标记为红色使人一目了然.我们可以通过 ES 提供的高亮功能实现此效果. 二.代码实现 前文查询是通过一个继承 Elasticsea ...
- Ros环境创建相关!超级简单!!超级详细!!
1.创建工作空间workspace 其中catkin_ws后面的ws是work_space的简写,指代工作空间 <catkin_ws是你的工作空间的名字,随便取> mkdir -p ~/c ...
- NOIP2024模拟12:孤帆远影
NOIP2024模拟12:孤帆远影 听了机房同学的讨论,于是T1死磕冒泡和逆序对做法.最后只得了40pts. 思想对了,但不是自己的做法. 还是要坚持自己想,坚持自己可以想出来,不要被任何人带偏. T ...
- 使用 vscode 简单配置 ESP32 连接 Wi-Fi 每日定时发送 HTTP 和 HTTPS 请求
最新博客文章链接 文字更新时间:2024/11/07 由于学校校园网,如果长时间不重新登陆的话,网速会下降,所以想弄个能定时发送 HTTP 请求的东西.由于不想给路由器刷系统,也麻烦.就开始考虑使用局 ...