You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Lighthouse GraphQL能否缓存API响应?替代方案咨询

GraphQL API响应缓存:Lighthouse的用法与替代方案

Lighthouse的@cache指令完全支持响应缓存

你提到的Lighthouse @cache查询指令就是专门用来实现API响应缓存的,而Schema缓存是另一回事——它只缓存Schema的解析结果,用于提升框架启动速度,和API请求的响应缓存无关。

@cache的用法很直接,可以直接在查询字段或者类型字段上添加,指定缓存有效期:

# 在查询类型的字段上添加缓存
type Query {
  user(id: ID!): User @cache(maxAge: 3600) # 缓存1小时
  publishedPosts: [Post!]! @cache(maxAge: 1800) # 缓存30分钟
}

# 也可以在类型的嵌套字段上添加
type User {
  id: ID!
  name: String!
  recentComments: [Comment!]! @cache(maxAge: 900) # 缓存15分钟
}

它会根据完整的查询内容+变量生成唯一缓存键,把响应结果存储到你配置的缓存驱动(Redis、文件、数据库等,Lighthouse默认兼容Laravel的缓存系统)中,到期自动失效,完全能满足常规的响应缓存需求。

若@cache无法满足自定义需求,可采用以下方案

如果需要更复杂的缓存逻辑(比如自定义缓存键、基于用户权限的缓存、部分响应缓存等),可以用以下两种方式:

1. 自定义Laravel中间件实现全局缓存

在请求进入GraphQL处理器之前,先检查缓存:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Cache;

class GraphQLCache
{
    public function handle($request, Closure $next)
    {
        // 提取查询和变量,生成唯一缓存键
        $query = $request->input('query');
        $variables = $request->input('variables', []);
        $cacheKey = 'graphql_response:' . md5($query . json_encode($variables));

        // 缓存命中则直接返回
        if (Cache::has($cacheKey)) {
            return response()->json(Cache::get($cacheKey));
        }

        // 执行请求并缓存成功响应
        $response = $next($request);
        if ($response->getStatusCode() === 200) {
            Cache::put($cacheKey, json_decode($response->getContent(), true), now()->addMinutes(30));
        }

        return $response;
    }
}

将这个中间件注册到你的GraphQL路由上即可生效。

2. 在Resolver中手动实现数据层缓存

如果只需要针对特定数据查询做缓存,可以直接在Resolver逻辑里处理:

public function resolveUser($root, array $args)
{
    $cacheKey = 'user_' . $args['id'];
    // 缓存用户数据1小时
    return Cache::remember($cacheKey, 3600, function () use ($args) {
        return \App\Models\User::with(['posts'])->findOrFail($args['id']);
    });
}

这种方式灵活性最高,适合需要精细控制缓存粒度的场景。

内容的提问来源于stack exchange,提问作者Hassan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 14:02:10