办公效率

Magento索引与缓存调优方案

排查商品价格或可见性异常,规划索引更新、Varnish 全页缓存和 Redis 会话及应用缓存。

# Magento 索引与缓存

## 概述

Magento 的性能架构依赖两个不同的层:索引器将反规范化数据(产品价格、搜索索引、分类路径)预先计算并存入扁平表;全页面缓存(FPC)则存储完整渲染后的 HTML 页面。生产环境推荐使用 Varnish 作为 FPC 后端,替代 Magento 内置的文件缓存。应用缓存、会话存储和默认缓存(区块 HTML、配置、布局)推荐使用 Redis 作为后端。索引配置错误或过期,是价格不正确和产品显示问题最常见的原因之一。

## 何时使用本技能

- 目录更新后产品价格显示错误或产品不可见时
- 首次在 Magento 生产服务器上部署 Varnish 时
- 诊断因实时计算价格导致的分类页面加载缓慢时
- 配置 Redis 以存储 Magento 会话和区块缓存时
- 设置通过 Magento 缓存标签在目录或 CMS 更新后使缓存失效时
- 管理大型目录(> 50,000 个产品)的索引器计划,以防止全量重建索引时锁表

## 核心指令

1. **了解 Magento 索引器及其模式**

   ```bash
   # List all indexers and their status
   bin/magento indexer:info
   bin/magento indexer:status

   # Example output:
   # catalog_category_product    Category Products    valid    Update on Save
   # catalog_product_category    Product Categories   valid    Update on Save
   # catalog_product_price       Product Price        invalid  Update by Schedule
   # catalogsearch_fulltext      Catalog Search       valid    Update by Schedule
   # catalogrule_product         Catalog Rule Product invalid  Update on Save
   ```

   将所有生产环境索引器设置为 `Update by Schedule` 模式,以防止结账被阻塞:

   ```bash
   bin/magento indexer:set-mode schedule catalog_category_product
   bin/magento indexer:set-mode schedule catalog_product_price
   bin/magento indexer:set-mode schedule catalogsearch_fulltext
   bin/magento indexer:set-mode schedule catalog_product_flat
   bin/magento indexer:set-mode schedule catalog_category_flat

   # Verify modes
   bin/magento indexer:show-mode
   ```

2. **管理索引器和部分重建索引**

   ```bash
   # Reindex a single indexer (less disruptive than full reindex)
   bin/magento indexer:reindex catalog_product_price

   # Reindex all (avoid on production during business hours)
   bin/magento indexer:reindex

   # Reset indexer to "invalid" to force next scheduled run
   bin/magento indexer:reset catalog_product_price

   # Check mview (materialized view) changelog tables — lists pending rows to process
   bin/magento indexer:show-changelog
   ```

   对于非常大的目录,使用并行索引:

   ```bash
   # app/etc/env.php — enable parallel processing
   # In Admin → System → Index Management → Indexers → Configure
   # Or via config:
   bin/magento config:set dev/grid/async_indexing 1
   ```

   ```php
   <?php
   // app/etc/env.php
   return [
       // ...
       'indexer' => [
           'batch_size' => [
               'catalog_product_price' => ['simple' => 200, 'configurable' => 50],
               'catalogsearch_fulltext' => ['simple' => 500],
           ],
       ],
   ];
   ```

3. **将 Varnish 配置为全页面缓存**

   ```bash
   # In Admin → System → Configuration → Advanced → System → Full Page Cache
   # Set Caching Application: Varnish Cache
   # Export Varnish configuration:
   bin/magento varnish:vcl:generate --export-version=6 --output-file=/etc/varnish/magento.vcl
   ```

   需要了解生成的 VCL 中的关键部分:

   ```vcl
   # /etc/varnish/magento.vcl (excerpts from generated config)

   sub vcl_recv {
       # Do not cache if private cookie is set (logged-in customer)
       if (req.http.cookie ~ "X-Magento-Vary=") {
           # Magento sets this cookie to vary cache by context (customer group, currency)
           # The cookie value changes only when the context changes — not per session
       }

       # Strip _ga, fbclid, utm_* params from cache key to prevent cache fragmentation
       set req.url = regsuball(req.url, "(\?|&)(utm_[^&]+|fbclid|gclid|mc_[^&]+)(&|$)", "\1");
   }

   sub vcl_hash {
       # Include Magento's context cookie in the cache hash
       if (req.http.cookie ~ "X-Magento-Vary=") {
           hash_data(regsub(req.http.cookie, ".*X-Magento-Vary=([^;]+).*", "\1"));
       }
   }

   sub vcl_backend_response {
       # Respect Magento's Cache-Control headers
       if (beresp.http.Cache-Control ~ "no-store") {
           set beresp.uncacheable = true;
           set beresp.ttl = 120s;
       }

       # Strip Set-Cookie on cacheable responses
       if (beresp.ttl > 0s) {
           unset beresp.http.set-cookie;
       }
   }
   ```

4. **配置 Redis 以用于应用缓存和会话**

   ```php
   <?php
   // app/etc/env.php — Redis cache and session configuration

   return [
       'cache' => [
           'frontend' => [
               'default' => [
                   'id_prefix' => 'b0c_',
                   'backend' => 'Magento\\Framework\\Cache\\Backend\\Redis',
                   'backend_options' => [
                       'server'            => '127.0.0.1',
                       'database'          => '0',
                       'port'              => '6379',
                       'password'          => '',
                       'compress_data'     => '1',
                       'compression_lib'   => 'gzip',
                       'persistent'        => 'mgto_cache',
                   ],
               ],
               'page_cache' => [
                   'id_prefix' => 'b0c_',
                   'backend' => 'Magento\\Framework\\Cache\\Backend\\Redis',
                   'backend_options' => [
                       'server'        => '127.0.0.1',
                       'database'      => '1', // Separate DB for FPC
                       'port'          => '6379',
                       'compress_data' => '0', // FPC data is already compressed HTML
                   ],
               ],
           ],
       ],
       'session' => [
           'save'                  => 'redis',
           'redis' => [
               'host'              => '127.0.0.1',
               'port'              => '6379',
               'password'          => '',
               'timeout'           => '2.5',
               'persistent_identifier' => 'mgto_sessions',
               'database'          => '2', // Separate DB for sessions
               'compression_threshold' => '2048',
               'compression_library'   => 'gzip',
               'log_level'             => '1',
               'max_concurrency'       => '6',
               'break_after_frontend'  => '5',
               'max_lifetime'          => '7200',
               'disable_locking'       => '1', // Improves performance but reduces session safety
           ],
       ],
   ];
   ```

5. **为自定义模块实现缓存标签失效**

   数据发生变化时,Magento 使用缓存标签选择性地使缓存页面失效。自定义模块应正确标记并清理缓存:

   ```php
   <?php
   // Declare cache tags in your block/model
   namespace MyVendor\CustomModule\Block;

   use Magento\Framework\View\Element\Template;
   use Magento\Framework\DataObject\IdentityInterface;

   class CustomProductWidget extends Template implements IdentityInterface
   {
       private array $productIds = [];

       public function getIdentities(): array
       {
           // Return cache tags so Magento invalidates this block when any of these products change
           $tags = [\Magento\Catalog\Model\Product::CACHE_TAG];
           foreach ($this->productIds as $id) {
               $tags[] = \Magento\Catalog\Model\Product::CACHE_TAG . '_' . $id;
           }
           return $tags;
       }
   }
   ```

   ```php
   <?php
   // In your observer or command — flush only relevant pages after product update
   namespace MyVendor\CustomModule\Observer;

   use Magento\Framework\Event\ObserverInterface;
   use Magento\Framework\App\Cache\TypeListInterface;
   use Magento\PageCache\Model\Cache\Type as PageCacheType;

   class ProductSaveObserver implements ObserverInterface
   {
       public function __construct(
           private readonly TypeListInterface $cacheTypeList,
           private readonly \Magento\Framework\App\Cache\Tag\Resolver $tagResolver
       ) {}

       public function execute(\Magento\Framework\Event\Observer $observer): void
       {
           $product = $observer->getEvent()->getProduct();

           // Invalidate only pages tagged with this product's cache tag
           // Varnish will purge via PURGE request using X-Magento-Tags-Pattern header
           $this->cacheTypeList->invalidate(PageCacheType::TYPE_IDENTIFIER);
       }
   }
   ```

## 示例

### 诊断索引滞后导致价格错误

```bash
# Check if mview changelog has pending rows
bin/magento indexer:show-changelog

# If catalog_product_price has > 0 pending rows, prices are stale
# Run the indexer to catch up
bin/magento indexer:reindex catalog_product_price

# Check cron_schedule table for missed cron jobs (should run indexers every minute)
bin/magento cron:run --group index &
# Or manually via:
mysql -u root -e "SELECT job_code, status, finished_at FROM magento.cron_schedule WHERE job_code LIKE '%index%' ORDER BY finished_at DESC LIMIT 20;"
```

### 部署后预热 FPC

```bash
#!/bin/bash
# scripts/warm-cache.sh — warm the FPC after deploy
set -e

MAGENTO_BASE_URL="https://www.mystore.com"
SITEMAP_URL="$MAGENTO_BASE_URL/sitemap.xml"

echo "Flushing Magento caches..."
bin/magento cache:flush

echo "Warming FPC via sitemap..."
# Download sitemap and curl each URL with a warm-cache header
curl -s "$SITEMAP_URL" | \
  grep -oP '<loc>\K[^<]+' | \
  head -500 | \
  xargs -P 10 -I {} curl -s -o /dev/null -w "%{http_code} {}\n" \
    -H "X-Warm-Cache: 1" {}

echo "Cache warming complete."
```

## 最佳实践

- **生产环境始终使用 `Update by Schedule` 模式** — `Update on Save` 会在后台保存时同步重建索引,导致大型目录超时
- **为缓存、FPC 和会话分别使用不同的 Redis 数据库** — 所有内容都使用数据库 0 会导致键冲突,且无法只清空其中一种类型
- **使用 `IdentityInterface` 标记自定义区块** — 这可确保数据变化时 Varnish 和 Magento 的 FPC 使正确的页面失效
- **监控索引器变更日志表的大小** — 有数百万行的 `catalog_product_price_cl` 表表明 cron 未运行;应在表大小导致重建索引超时之前修复 cron
- **使用 `bin/magento cache:clean` 而非 `cache:flush`** — `clean` 仅移除无效的缓存条目(安全);`flush` 会清空所有内容,包括共享同一个 Redis 的其他框架缓存
- **为每个环境设置不同的 `id_prefix`** — 预发布环境和生产环境可以共享 Redis 服务器,只要各自使用唯一前缀,即可防止缓存污染
- **使用 `curl -I` 和 `X-Cache` 标头测试 Varnish** — `HIT` 响应确认 Varnish 正在从缓存提供内容;`MISS` 则意味着每个请求都访问 Magento

## 常见陷阱

| 问题 | 解决方案 |
|---------|----------|
| 导入后产品不可见或价格错误 | 批量导入后运行 `bin/magento indexer:reindex` — 如果直接使用 `ResourceModel\Product::save`,以编程方式保存产品并不总会触发索引器 |
| Varnish 向已登录客户提供过期页面 | 确保 `X-Magento-Vary` cookie 包含在 Varnish VCL 哈希中;已登录客户会获得不同的 vary 值,从而绕过共享缓存 |
| Redis 内存耗尽 | 对缓存数据库,在 `redis.conf` 中设置 `maxmemory-policy allkeys-lru`;对会话数据库,使用 `noeviction` 防止会话悄然丢失 |
| 保存产品后 FPC 未失效 | 检查 Varnish 的 PURGE ACL 是否允许来自 Magento 服务器 IP 的请求;使用 `curl -X PURGE http://varnish-ip/` 测试  |
| 全量重建索引耗时数小时并锁表 | 在 `env.php` 中启用索引器批次大小设置,并使用 `--mode realtime` 运行以进行部分重建索引;安排在非高峰时段执行 |
| Cron 索引器未运行 | 检查 `var/log/magento.cron.log` 中的错误;确认系统 crontab 条目以 Web 服务器用户身份每分钟运行一次 `bin/magento cron:run` |

## 相关技能

- @magento-module-development
- @magento-graphql
- @magento-multi-store
- @caching-strategies
- @infrastructure-performance

同类提示词

办公效率· n8n 工作流的对话模型

商品照片转棚拍广告生图指令

上传商品照片并提供说明文字,分析材质、配色和原图问题,写出保留商品外观的棚拍广告生图指令。

=你是一位专业产品摄影师和广告创意总监。分析上传的产品图片及其配文:{{ $('Telegram Trigger Received').item.json.message.caption }} 你的任务是创建一段详细的图像生成提示词,将这张产品照片转化为高端、商业级的广告视觉作品。 分析要求: 1. **产品识别**:识别产品类型、尺寸、类别、材质、配色和关键特征 2. **当前状态评估**:指出当前的光线、背景、构图和质量问题 3. **目标美学**:根据产品类别确定理想的广告风格(奢侈品、科技、食品、时尚等) 输出(严格使用 JSON 格式):
办公效率· n8n 工作流的对话模型

Veo 3营销视频分镜指令

填写视频需求、营销目标、图像描述和画幅,生成包含场景、运镜、动作、灯光与结尾的结构化制片指令。

=# Veo3 视频生成系统提示词 你是一名专业的视频提示词工程师,擅长为 Veo3 视频生成撰写细致、富有电影感的提示词。你的角色是分析用户输入,将其转化为全面的视频生成指令,以产出高质量、引人入胜的内容。 ## 输入分析 你将收到以下用户输入: - **AI Videos instructions**:视频生成的核心用户请求 - **Campaign objectives**:营销活动目标和说明 - **Images Description**:用户提供的视觉背景信息 - **Aspect Ratio**:要求的视频尺寸比例 ## 输出格式 你
可填 21 项
办公效率· n8n 工作流的对话模型

保留原品的社媒广告视觉方案

提供商品图和配文,生成保留原品外观的广告生图说明,广告文字仅从配文提取,缺项留空。

={ "system_prompt": "你是一位顶尖创意总监,专攻爆款产品广告,拥有15年以上奢侈品牌广告活动经验。将产品图片转化为商业级广告,让浏览者停下滑动并促进转化。", "instructions": { "core_rules": [ "保持原始产品100%不变——不得修改、替换或扭曲", "只提取和使用用户配文中提供的文字", "如果配文中没有相关文字,文字字段留空——绝不生成AI广告语", "专注于高端视觉强化和商业摄影技巧", "制作适合在Instagram展
办公效率· Claude Fable 5.2

用代码制作长纪录片流程

从题材调研、脚本和样帧审核开始,按章节生成三维分镜、旁白、环境声与可复现渲染。

<inputs> 向我询问: 1. 我的主题 2. 目标视频时长 3. 我是否已有脚本 如果我只给你一个主题,先研究该主题并撰写脚本。 开始制作任何内容之前,先向我展示: - 完整脚本 - 章节拆分 - 前 60 seconds 的分镜计划 - 6 张展示预期视觉方向的静帧 在我认可视觉效果之前,不要渲染完整视频。 </inputs> <story> 按照高品质 YouTube 纪录片的方式来写,不要写成 AI 科普解说。 故事必须始终向前推进。 每个部分都需要包含以下内容之一: - 一个新问题 - 一个揭示 - 一个矛盾 - 一个后果 - 一条证据
办公效率

同场景表情变化九宫格自拍

上传主角照片,可选搭档参考图或设定,并填写服装、背景或姿势偏好,生成同一布光和构图的九张变化。

# photo-booth ## 何时使用此 skill - 当用户希望根据参考图制作大头贴宫格、表情宫格、情侣自拍宫格、同步姿势组图或多种人像变体时使用。 - 当请求制作 3x3 宫格,且主体、房间、服装、构图和布光保持一致,仅表情或细微姿势发生变化时触发。 ## 必需输入 - 主要人物的主参考图。 - 可选的伴侣或角色参考图。 - 如果未提供伴侣参考图,需提供期望的伴侣设定。 - 用户指定的服装、背景、摄影时代、姿势清单或氛围。 如果缺少主参考图,请用户附上。如果伴侣设定或预期风格不明确,提出一个有针对性的问题。 ## 连续性规则 -
需参考图
办公效率· Claude Code / 动效编程

单镜头立体落地页飞越动画

提供落地页链接、品牌名、标志和两段收尾文案,可选配乐,制作卡片随镜头掠过而浮起的连续飞越短片。

<inputs> 向我索取:我的落地页链接、品牌名称和标志、由两部分组成的结尾文案(一句陈述,后接一小段斜体文字),以及一条 15 second 音轨(可选)。 </inputs> <direction> 以 60fps 对我的落地页进行 14.5 second 3D 飞越拍摄,1440x1152。页面平放在明亮的摄影棚地面上(中央为 #f9fbfb,角落为 #f2f3f6),周围有柔和宽阔的阴影,圆角为 24px。全程使用一个连续镜头,绝不切镜:镜头从首屏上方低处开始,以恒定速度沿页面向后滑行,同时朝页面上方看去;然后垂直升至正上方,将整个页面呈现为
✓