# 5.10 字典模块 :::tip 概述 字典是枚举数据的唯一真相:dict(字典)+ dict_item(字典项)两级结构,驱动全系统的 {field}Text 显示名。文案修改在字典管理页完成,无需改代码。 ::: ## 数据结构 ```text goframe_dict 字典表:name / code(uk_code 全局唯一)/ sort goframe_dict_item 字典项表:dict_id / name / value / sort 示例(role_data_scope 字典): dict: { code: "role_data_scope", name: "数据范围" } dict_item: { name: "全部", value: 1 } { name: "本部门及以下", value: 2 } { name: "本部门", value: 3 } { name: "仅本人", value: 4 } ``` ## 字典编码规范 ```text 编码 = {模块snake}_{字段snake} 示例:user_status(用户-状态)、job_execute_policy(任务-执行策略)、 example_status(案例-状态)、role_data_scope(数据范围,公共字典) 创建途径: 1) 代码生成器 createDict:按列注释枚举自动创建(幂等,按 code 查重) 2) 字典管理页手工创建 ``` ## 接口清单 ```text /sys:dict:* 七件套(page/detail/add/update/delete/batchDelete;无 list,列表经 page) GET /api/dict/refreshCache sys:dict:cache 刷新字典缓存 GET /api/dictionary/list 登录即可 字典列表别名(前端 dictionary.ts) GET /api/dictionary/info 登录即可 字典详情别名 /sys:dictitem:* 七件套 GET /api/dict/item/getDictItemList/:code 登录即可 按编码查字典项(缓存) ``` 注意:dict 无 `/dict/list`,列表经 page 或 `/api/dictionary/list` 别名。 ## 缓存策略(两层) | 层 | 键/容器 | TTL | 失效 | |----|---------|-----|------| | Redis | `easygoadmin:dict:item:{code}` | 3600s | RefreshCache 主动重建;dict_item 变更不主动清(最长 1 小时延迟) | | 进程内 | dictTextCache({code}:{value} → 显示名) | 300s | 各实例自然过期 | 关键场景(改完文案要立即生效):调 `GET /api/dict/refreshCache` 刷新 Redis 层;进程内层最迟 5 分钟自然过期。 ## 在业务中的消费({field}Text) ```go // logic 模块头部声明(真实模式) var xxxSerializeMaps = map[string]string{ "status": "user_status", } // 基座读取时自动填充结构体的 {Field}Text 字段 // 取值链:DictGetText(ctx, "user_status", 1) → 查 dict→dict_item 的 name → 进程内缓存 ``` 详见 [5.11 字典配置与使用](./dict-guide)。 ## 与生成器的联动 ```text 建表时列注释写枚举:"状态:1-正常 2-禁用"(- — = = 均可作分隔) → 生成器 createDict 解析 → 自动创建 dict(name="{模块中文名}-{字段中文名}",note 标注自动创建) → 逐 Choice 建 dict_item(name=label, value, sort+5) → 结果逐项返回(已存在/创建成功/失败原因),幂等 ``` ## 运维要点 + 字典文案修改后,展示最迟 5 分钟(进程内层)生效;紧急场景调 refreshCache + 定稿种子已含 role_data_scope 等公共字典(随 SQL 脚本导入) + 字典 code 全局唯一(uk_code),创建前查重 + 非枚举字段不要建字典——{field}Text 只用于枚举列