You need to enable JavaScript to run this app. 如何在Netflix DGS Resolver中获取HTTP请求头信息
优惠活动
大模型
产品
解决方案
定价
更多

如何在Netflix DGS Resolver中获取HTTP请求头信息

现有查询Resolver层实现

我们可以按如下方式编写查询Resolver层:

@DgsData(parentType = "Query", field = "answersByQuestionUuid")
public List<Answer> answersByQuestionUuid(@InputArgument("questionUuid") UUID questionUuid,
                                          @InputArgument("enhancedContent") boolean enhancedContent,
                                          @InputArgument("templateName") String templateName)  {
    if (enhancedContent) {
        return getStructuredAnswersByQuestionUUID(questionUuid.toString(), templateName);
    }
    return getAnswersByQuestionUUID(questionUuid);
}
待解决的技术问题

如何在上述DGS Resolver中获取HTTP请求头信息?

具体实现方案
  • 基于Spring MVC Servlet环境的注入方式
    常规的Servlet栈DGS项目可以直接在Resolver方法参数中声明HttpServletRequest对象,Spring容器会自动将当前请求上下文的实例注入进来,不需要额外配置。改造后的代码示例:
    @DgsData(parentType = "Query", field = "answersByQuestionUuid")
    public List<Answer> answersByQuestionUuid(@InputArgument("questionUuid") UUID questionUuid,
                                              @InputArgument("enhancedContent") boolean enhancedContent,
                                              @InputArgument("templateName") String templateName,
                                              HttpServletRequest request) {
        // 直接调用getHeader方法读取对应请求头
        String userAuth = request.getHeader("Authorization");
        if (enhancedContent) {
            return getStructuredAnswersByQuestionUUID(questionUuid.toString(), templateName, userAuth);
        }
        return getAnswersByQuestionUUID(questionUuid);
    }
    
  • 公共逻辑层无侵入获取方式
    如果不需要在Resolver层直接传递请求对象,可以通过Spring提供的RequestContextHolder静态工具类,在任意业务代码位置获取当前请求上下文,不需要逐层传递参数:
    // 获取当前请求的属性
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    if (attributes != null) {
        HttpServletRequest currentRequest = attributes.getRequest();
        String traceId = currentRequest.getHeader("X-Trace-Id");
    }
    

注意:如果项目使用WebFlux响应式栈,上述两种Servlet相关的获取方式会出现上下文为null的问题,需要替换为注入ServerWebExchange对象,从中提取对应的请求头信息。

内容的提问来源于stack exchange,提问作者Umesh Singh Kushwaha

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.29 11:54:03