Shopware 6 API返回数据缓存方案咨询:自带缓存还是需用Symfony扩展?
在Shopware 6中缓存API返回数据的方案
一、Shopware 6自带的缓存能力
Shopware 6基于Symfony框架构建,天然继承了Symfony的缓存组件,同时也扩展了适配自身业务的缓存机制:
- 核心API中部分可缓存的端点(如产品列表、分类信息)已默认启用缓存,默认使用文件缓存池,可配置切换为Redis等外部存储。
- 自定义API开发时,可直接用Symfony的缓存注解或Shopware封装的缓存接口实现结果缓存,无需额外引入第三方扩展。
二、对接Redis等外部缓存服务
Shopware 6无需额外安装Symfony缓存扩展,只需修改配置即可将缓存驱动切换为Redis:
在config/packages/framework.yaml中更新缓存配置:
framework: cache: app: cache.adapter.redis default_redis_provider: redis://localhost:6379
配置生效后,包括API缓存在内的所有Shopware缓存都会自动存储到Redis中。
三、自定义API缓存的实现方式
方式1:使用缓存注解快速实现
在自定义API控制器的方法上添加Symfony的#[Cache]注解,指定缓存有效期、是否公开等参数:
use Symfony\Component\Cache\Annotation\Cache; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\Routing\Annotation\Route; #[Route('/api/v1/custom-product-list', name: 'api.custom.product.list', methods: ['GET'])] #[Cache(expires: '1 hour', public: true)] public function getCustomProductList(): JsonResponse { $data = $this->productRepository->search(...); // 数据库查询逻辑 return new JsonResponse($data); }
方式2:手动控制缓存逻辑(适用于复杂场景)
通过Shopware提供的CacheInterface实例,手动生成缓存键、控制缓存有效期,还能根据请求参数区分缓存:
use Shopware\Core\Framework\Cache\CacheInterface; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; #[Route('/api/v1/custom-product-detail', name: 'api.custom.product.detail', methods: ['GET'])] public function getCustomProductDetail(Request $request, CacheInterface $cache): JsonResponse { $productId = $request->query->get('id'); $cacheKey = 'product_detail_' . $productId; // 尝试从缓存获取,不存在则执行查询并写入缓存 $data = $cache->get($cacheKey, function() use ($productId) { return $this->productRepository->searchOneBy(['id' => $productId]); }, 3600); // 缓存1小时 return new JsonResponse($data); }
四、关键注意事项
- 缓存数据需确保是无用户特异性的通用数据;若需缓存用户专属数据,需在缓存键中加入用户ID等标识。
- 当数据更新时(如产品修改),需手动清除对应缓存键,可通过监听Shopware的数据变更事件(如
ProductWrittenEvent)触发缓存清理。 - 核心API的缓存TTL可通过
config/packages/shopware.yaml中的相关配置调整。
内容的提问来源于stack exchange,提问作者Ole Dahl Mansfeld
相关产品推荐
相关产品推荐

