项目中的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封装数据库及缓存模型的更多相关文章

  1. iOS数据库离线缓存思路和网络层封装

    一直想总结一下关于iOS的离线数据缓存的方面的问题,然后近期也简单的对AFN进行了再次封装.全部想把这两个结合起来写一下.数据展示型的页面做离线缓存能够有更好的用户体验,用户在离线环境下仍然能够获取一 ...

  2. ThinkPHP6.0在phpstorm添加查询构造器和模型的代码提示

    ThinkPHP6.0升级后 使用查询构造器和模型都没有了提示 原因是tp6源码中没有添加注释 找到Model.php * @method Query where(mixed $field, stri ...

  3. 第六十二篇、AFN3.0封装网络请求框架,支持缓存

    1.网络请求 第一种实现方式: 功能:GET POST 请求 缓存逻辑: 1.是否要刷新本地缓存,不需要就直接发起无缓存的网络请求,否则直接读取本地数据 2.需要刷新本地缓存,先读取本地数据,有就返回 ...

  4. Python之路,Day10 - 异步IO\数据库\队列\缓存

    Python之路,Day9 - 异步IO\数据库\队列\缓存   本节内容 Gevent协程 Select\Poll\Epoll异步IO与事件驱动 Python连接Mysql数据库操作 RabbitM ...

  5. python面试题库——3数据库和缓存

    第三部分 数据库和缓存(46题) 列举常见的关系型数据库和非关系型都有那些? 关系型数据库: Oracle.DB2.Microsoft SQL Server.Microsoft Access.MySQ ...

  6. 【原创】分布式之数据库和缓存双写一致性方案解析(三) 前端面试送命题(二)-callback,promise,generator,async-await JS的进阶技巧 前端面试送命题(一)-JS三座大山 Nodejs的运行原理-科普篇 优化设计提高sql类数据库的性能 简单理解token机制

    [原创]分布式之数据库和缓存双写一致性方案解析(三)   正文 博主本来觉得,<分布式之数据库和缓存双写一致性方案解析>,一文已经十分清晰.然而这一两天,有人在微信上私聊我,觉得应该要采用 ...

  7. 异步IO/协程/数据库/队列/缓存(转)

    原文:Python之路,Day9 - 异步IO\数据库\队列\缓存 作者:金角大王Alex add by zhj: 文章很长 引子 到目前为止,我们已经学了网络并发编程的2个套路, 多进程,多线程,这 ...

  8. 数据库与缓存:2.Redis数据库的基本知识

    1.属于什么类型的数据库 not only sql  非关系型数据库,与传统的关系型数据库不同,存储形式都是kv形式. 2.特点 几乎不支持事务,key-value形式存储,支持队列和缓存(可以设置数 ...

  9. JavaScript实现TwoQueues缓存模型

    本文所指TwoQueues缓存模型,是说数据在内存中的缓存模型. 无论何种语言,都可能需要把一部分数据放在内存中,避免重复运算.读取.最常见的场景就是JQuery选择器,有些Dom元素的选取是非常耗时 ...

  10. iOS超全开源框架、项目和学习资料汇总--数据库、缓存处理、图像浏览、摄像照相视频音频篇

    iOS超全开源框架.项目和学习资料汇总--数据库.缓存处理.图像浏览.摄像照相视频音频篇 感谢:Ming_en_long 的分享 大神超赞的集合,http://www.jianshu.com/p/f3 ...

随机推荐

  1. KubeSphere Helm 应用仓库源码分析

    作者:蔡锡生,LStack 平台研发工程师,近期专注于基于 OAM 的应用托管平台落地. 背景介绍 KubeSphere 应用商店简介 作为一个开源的.以应用为中心的容器平台,KubeSphere 在 ...

  2. KubeSphere 社区双周报 | 4.8 深圳站 Meetup 火热报名中 | 2023.3.17-3.30

    KubeSphere 社区双周报主要整理展示新增的贡献者名单和证书.新增的讲师证书以及两周内提交过 commit 的贡献者,并对近期重要的 PR 进行解析,同时还包含了线上/线下活动和布道推广等一系列 ...

  3. 云原生爱好者周刊:使用树莓派组建 K8s 集群 | 2022-08-08

    开源项目推荐 Raspberry Pi Kubernetes Cluster 这是一个教育项目,旨在探索如何在家中使用树莓派构建 Kubernetes 集群,并使用 Ansible 来自动化部署和配置 ...

  4. KubeSphere DevOps 流水线入门指南

    作者:赵海亮,浙江大学计算机专业四年级在读博士生,研究方向为云计算.边缘计算.分布式系统等. 虽然 KubeSphere 能够将我们从 yaml 文件的编写中解放出来,但是项目上云仍然十分繁琐. 此外 ...

  5. activiti教程

    一.工作流介绍 1.1 概念 工作流(Workflow),就是通过计算机对业务流程自动化执行管理.它主要解决的是"使在多个参与者之间按照某种预定义的规则自动进行传递文档.信息或任务的过程,从 ...

  6. Shell简单入门程序参考

    目录 0 前言 0.1 shell初试 1 程序功能 1.1 显示当前主机名和IP地址. 1.1.1 if 语句 详解 1.2 创建目录或者文件 1.3 修改文件属性 1.3.1 chmod 修改文件 ...

  7. 3.7 Linux切换目录(cd命令)

    cd 命令,是 Change Directory 的缩写,用来切换工作目录. Linux 命令按照来源方式,可分为两种,分别是 Shell 内置命令和外部命令.所谓 Shell 内置命令,就是 She ...

  8. 2个月搞定计算机二级C语言——真题(10)解析

    1. 前言 本篇我们讲解2个月搞定计算机二级C语言--真题10 2. 程序填空题 2.1 题目要求 2.2 提供的代码 #include <stdio.h> #pragma warning ...

  9. 如何挑选海外4G模组?这里有秘籍!

    今天我会告诉大家如何挑选海外4G模组,我会把优势给贴出作为参考.去过国外的都知道国外4G网络各种状况实在让人无力吐槽,做海外设备的朋友,是时候了解一下Air780EEN/EEU/EEJ系列海外模组-- ...

  10. curl访问etcd报错unable to set private key file

    [appdeploy@1a32vla0168zzzz cfssl]$ curl -i https://xxx.xxx.xxx.5:2379/health --cacert /app/etcd/cfss ...