Files
rxthinkcmf-wiki/RXThinkCMF_ThinkPhp8_EleVue/zh/architecture/cache.md
T
2026-09-29 10:14:04 +08:00

90 lines
3.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 4.8 缓存架构设计
:::tip 概述
项目采用两级缓存架构:请求级缓存(内存)+ 持久缓存(file/Redis),大幅减少数据库查询。
:::
## 两级缓存架构
```text
┌─────────────────────────────────────────────────────────┐
│ 第一级:请求级缓存(static 变量) │
│ │
│ 生命周期:单次 HTTP 请求 │
│ 存储位置:PHP 内存(static $cache) │
│ 速度:极快(纳秒级) │
│ │
│ 同一请求内多次查询同一数据,只查一次库或缓存 │
└──────────────────────────┬──────────────────────────────┘
│ 未命中
▼
┌─────────────────────────────────────────────────────────┐
│ 第二级:持久缓存(cache() 门面) │
│ │
│ 生命周期:跨请求复用 │
│ 存储位置:file 或 Redis │
│ 速度:快(毫秒级) │
│ 有效期:1 小时(3600 秒) │
│ │
│ 跨请求复用,减少数据库压力 │
└──────────────────────────┬──────────────────────────────┘
│ 未命中
▼
┌─────────────────────────────────────────────────────────┐
│ 数据库查询 │
│ │
│ 查询后同时写入两级缓存 │
└─────────────────────────────────────────────────────────┘
```
## 使用两级缓存的服务
| 服务 | 缓存键格式 | 说明 |
|------|-----------|------|
| `DictService` | `dict_{code}` | 字典项映射 |
| `DictService` | `dict_full_{code}` | 字典项完整数据 |
| `ParamService` | `param_{code}` | 系统参数值 |
## 缓存驱动配置
`.env` 配置:
```ini
; 文件缓存(默认)
[CACHE]
DRIVER = file
; Redis 缓存(推荐生产环境)
[CACHE]
DRIVER = redis
REDIS_HOST = 127.0.0.1
REDIS_PORT = 6379
REDIS_PASSWORD =
REDIS_DB = 0
```
:::warning 生产环境建议使用 Redis
文件缓存在多进程/多服务器环境下无法共享,生产环境建议配置 Redis 缓存驱动。使用 Redis 前需安装 `php redis` 扩展。
:::
## 缓存清除
```php
// 清除指定字典缓存
DictService::clearCache('gender');
// 清除所有字典缓存
DictService::clearAllCache();
// 清除指定参数缓存
ParamService::clearCache('DEFAULT_PASSWORD');
// 清除所有参数缓存
ParamService::clearAllCache();
```
对应接口:
```text
GET /api/dict/refreshCache 刷新字典缓存
```