如何把 TensorFlow Lite 模型加载到 Struts 拦截器?

解读

在国内企业级 Java Web 面试中,面试官提出“把 TensorFlow Lite 模型加载到 Struts 拦截器”并不是想让你现场写一段 AI 代码,而是考察三点:

  1. 你是否真正理解 Struts 拦截器的生命周期与线程安全边界;
  2. 你是否知道Java 与 Native 模型文件(.tflite)的加载套路;
  3. 你是否能在高并发 Web 场景下给出内存、性能、安全都可落地的方案。

因此,回答必须围绕“拦截器里只放轻量级引用,模型推理下沉到单例服务”这一核心思路展开,切忌直接把 Interpreter 塞进拦截器成员变量。

知识点

  1. Struts 拦截器栈配置:struts.xml 中通过 <interceptor-stack> 把自定义拦截器插入默认栈,保证顺序在 params 与 workflow 之前。
  2. 拦截器线程安全:Struts2 每次请求会新建 ActionInvocation 实例,但拦截器实例是全局单例,因此禁止在 intercept() 方法内直接 new Interpreter()。
  3. TensorFlow Lite Java API 加载路径:
    • 模型文件必须放在Web 容器之外的受保护目录(如 /opt/ai/models/),避免被用户下载;
    • 使用 MappedByteBuffer.load() 把 .tflite 映射到堆外内存,减少 GC 压力;
    • 通过 Interpreter.Options.setNumThreads(Integer.parseInt(StrutsUtil.getProperty("tflite.threads"))) 实现线程池大小可配置。
  4. Spring 与 Struts 整合:国内项目 90% 用 Spring 管 Bean,因此把 TfliteInferenceService 声明为 @Service("tfliteService"),在拦截器里通过 ServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) 拿到 Spring 上下文,再 getBean(),避免硬编码 new。
  5. 模型热更新:利用 commons-vfs2 监听模型目录,当 *.tflite 文件 lastModified 变化时,调用 Interpreter.close() 并重新 MappedByteBuffer.load(),保证不停机更新。
  6. 安全与限流:在拦截器里先取 HttpServletRequest.getParameter("uid") 做风控白名单校验,再调用模型,防止恶意调用导致 GPU/CPU 打满。

答案

步骤一:在 Spring 中声明线程安全的模型服务

@Service("tfliteService")
public class TfliteInferenceService {
    private volatile Interpreter interpreter;
    private final String modelPath = "/opt/ai/models/fraud.tflite";
    @PostConstruct
    public void init() throws IOException {
        reload();
    }
    public synchronized void reload() throws IOException {
        if (interpreter != null) interpreter.close();
        MappedByteBuffer buffer = FileChannel.open(Paths.get(modelPath), StandardOpenOption.READ)
                                             .map(FileChannel.MapMode.READ_ONLY, 0, Files.size(Paths.get(modelPath)));
        Interpreter.Options opt = new Interpreter.Options().setNumThreads(4);
        interpreter = new Interpreter(buffer, opt);
    }
    public float predict(float[] input) {
        float[][] output = new float[1][1];
        interpreter.run(input, output);
        return output[0][0];
    }
}

步骤二:自定义拦截器,只持有服务引用,不持有模型

public class AiRiskInterceptor extends AbstractInterceptor {
    private TfliteInferenceService tfliteService;
    @Override
    public void init() {
        WebApplicationContext wac = (WebApplicationContext) ServletActionContext.getServletContext()
                   .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        tfliteService = wac.getBean("tfliteService", TfliteInferenceService.class);
    }
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        HttpServletRequest req = ServletActionContext.getRequest();
        String uid = req.getParameter("uid");
        // 白名单+限流逻辑省略
        float score = tfliteService.predict(new float[]{uid.hashCode()});
        if (score > 0.85f) {
            return "risk_block";
        }
        return invocation.invoke();
    }
}

步骤三:在 struts.xml 中把拦截器插入默认栈

<interceptor name="aiRisk" class="com.xxx.interceptor.AiRiskInterceptor"/>
<interceptor-stack name="aiDefaultStack">
    <interceptor-ref name="aiRisk"/>
    <interceptor-ref name="defaultStack"/>
</interceptor-stack>
<default-interceptor-ref name="aiDefaultStack"/>

通过以上三步,模型加载与推理完全与 Struts 生命周期解耦,满足国内金融级场景对线程安全、热更新、可运维的硬性要求。

拓展思考

  1. 如果模型体积超过 200 MB,MappedByteBuffer 会占用大量堆外内存,可考虑TensorFlow Lite 的 GPU Delegate,但需要在服务器安装 OpenCL 驱动,此时拦截器只需把输入向量转给 GPU 服务即可,推理不再本地 JVM。
  2. 当 QPS 超过 1 万,单实例 Interpreter 成为瓶颈,可引入 TensorFlow Serving + gRPC,拦截器里通过 Netty 非阻塞客户端调用,把 AI 逻辑彻底迁出 Web 容器,Struts 只负责网关层风控。
  3. 国内等保 2.0 要求模型文件完整性校验,可在 reload() 时先计算 SM3 摘要,与运维平台下发的签名对比,防止模型被篡改导致业务绕过。
  4. 若项目已迁到 Spring Boot + Struts2 混合架构,可用 @PostConstruct 配合 Nacos @NacosConfigListener 实现动态线程池参数与模型路径的统一配置,减少重启次数,这是面试官最爱问的“云原生”加分点。