当超出套餐额度时,如何返回 402 Payment Required?

解读

国内互联网项目普遍采用“按量计费 + 套餐额度”模式,当用户调用量超过套餐上限,后端必须立即拒绝服务并给出402 Payment Required状态码,提示前端“余额不足,请充值”。
在 Apache Struts 2 场景下,该需求通常落在拦截器层或自定义结果类型里实现,既要与业务解耦,又要保证高并发线程安全,还要兼容 Nginx、SLB 等网关的缓存策略。
面试官重点考察:

  1. 是否知道 Struts 2 拦截器栈扩展点;
  2. 是否理解 402 语义与 HTTP 状态码规范;
  3. 能否给出可灰度、可配置、无侵入的落地方案。

知识点

  1. Struts 2 拦截器生命周期:pre-processing → ActionInvocation.invoke() → post-processing;
  2. Struts 2 结果类型:默认 dispatcher,可自定义继承 StrutsResultSupport 的 Result;
  3. HttpServletResponse.sendError(int, String) 可强制返回 4xx/5xx 并清空缓冲区;
  4. 402 状态码在 RFC 7231 中定义为“Payment Required”,国内云厂商普遍支持;
  5. 套餐额度建议放在分布式缓存(Redis + Lua 脚本)原子扣减,避免并发超卖;
  6. Nginx 默认缓存 4xx 仅 1 分钟,若需立即生效应加 Cache-Control: no-cache, no-store。

答案

步骤一:定义额度拦截器

public class QuotaInterceptor extends AbstractInterceptor {
    private static final String QUOTA_KEY_PREFIX = "quota:";
    private RedisTemplate<String, Integer> redisTemplate; // 注入

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        String userId = invocation.getInvocationContext().getSession().get("userId").toString();
        String key = QUOTA_KEY_PREFIX + userId;
        Long remain = redisTemplate.opsForValue().decrement(key);
        if (remain != null && remain >= 0) {
            return invocation.invoke(); // 正常通过
        }
        // 额度耗尽
        HttpServletResponse response = ServletActionContext.getResponse();
        response.sendError(402, "Payment Required: 套餐额度已用完,请前往控制台升级套餐");
        return Action.NONE; // 终止后续流程
    }
}

步骤二:注册拦截器栈
在 struts.xml 中全局生效,只拦截需要计费的 package:

<package name="api" extends="json-default">
    <interceptors>
        <interceptor name="quota" class="com.xxx.interceptor.QuotaInterceptor"/>
        <interceptor-stack name="apiStack">
            <interceptor-ref name="quota"/>
            <interceptor-ref name="defaultStack"/>
        </interceptor-stack>
    </interceptors>
    <default-interceptor-ref name="apiStack"/>
</package>

步骤三:网关与浏览器验证

  • 浏览器 DevTools 看到 Status Code: 402 Payment Required;
  • 前端根据 402 弹窗“立即充值”,避免重试造成雪崩;
  • 若后端前面还有 Nginx,需在 proxy_intercept_errors off 状态下透传 402。

拓展思考

  1. 灰度策略:利用 Struts 2 拦截器参数注入,给内部员工设置 quota_skip=true,动态白名单;
  2. 精度控制:Redis 采用 Lua 脚本保证“扣减 + 判断”原子性,防止并发瞬间击穿;
  3. 多维度额度:除“调用次数”外,可扩展 QPS、带宽、CPU 时长等维度,复用同一拦截器模板;
  4. 账单回调:返回 402 后异步推送消息到 MQ,账单系统实时生成“欠费订单”,提升付费转化率;
  5. 兼容旧客户端:部分旧 SDK 只认 200,可在 402 响应体里再包一层 {"code":402,"msg":"Payment Required"},双通道兼容;
  6. 安全加固:402 响应必须带 X-Content-Type-Options: nosniff,防止网关缓存篡改,避免用户敏感信息泄露。