如何注册 Fabric 事件并触发 Struts 业务回调?
解读
国内大多数 Struts 项目运行在 政务、金融、运营商 等“强监管”场景,面试官问“Fabric 事件”并不是让你讲区块链源码,而是考察两点:
- 你是否理解 Struts 的拦截器/监听器扩展点;
- 你是否能把 外部事件总线(如 Hyperledger Fabric 的 ChaincodeEvent、或者公司自研的 MQ) 桥接到 Struts 业务线程,并保证 事务一致性、线程安全、审计可追溯。
一句话:让链下 Struts 应用“订阅”链上事件,然后“回调”到已经配置好的 Struts Action,形成 “事件驱动 + MVC” 的混合架构。
知识点
- Struts 自定义拦截器栈:通过
<interceptor-stack name="fabricStack">把自定义拦截器插入默认栈,保证事件回调也能复用验证、鉴权、日志等横切逻辑。 - Servlet 3.0 异步上下文:在
StrutsPrepareAndExecuteFilter里开启request.startAsync(),避免 Fabric 的 gRPC 长连接阻塞 Tomcat 工作线程。 - Spring 托管的 Fabric SDK Bean:国内项目几乎 100% 用 Spring 管理事务,因此把
HFClient、Channel、EventHub全部配成 Spring 单例,再注入到 Struts 的ServletContextListener,实现 “容器级”生命周期对齐。 - OGNL 安全加固:事件 payload 里若含用户输入,必须走 Struts 的
params拦截器二次过滤,防止 OGNL 注入(国内护网行动重点检查项)。 - 日志与审计:按照 《金融行业应用日志规范》,事件 ID、区块高度、交易 hash、Struts Action 名称、用户会话 ID 必须 一条不落 地写到 ELK,方便等保 2.0 倒查。
答案
步骤一:在 web.xml 增加 Spring 监听器,保证 Fabric SDK 比 Struts 先启动
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-fabric.xml</param-value>
</context-param>
步骤二:Spring-fabric.xml 里注册 FabricEventBridge
<bean id="fabricEventBridge" class="com.xxx.FabricEventBridge" init-method="start" destroy-method="shutdown">
<property name="channelName" value="mychannel"/>
<property name="eventName" value="struts/invoke"/>
<property name="strutsActionName" value="fabricCallback"/>
</bean>
步骤三:FabricEventBridge 实现 EventHub 监听,收到事件后 不直接写业务表,而是把 payload 封装成 Map<String,Object>,通过 ServletContext 拿到 ActionProxyFactory,动态调用已注册的 Struts Action
public void onEvent(BlockEvent.TransactionEvent event){
String json = new String(event.getPayload(), StandardCharsets.UTF_8);
Map<String,Object> params = JSON.parseObject(json);
// 构造 Struts 上下文
ActionContext ctx = new ActionContext(ServletActionContext.getContext().getContextMap());
ctx.put("fabric.params", params);
ActionProxy proxy = actionProxyFactory.createActionProxy(
"", "fabricCallback", null, ctx.getContextMap());
proxy.execute();
}
步骤四:在 struts.xml 中声明免表单 token 的回调 Action,防止重复提交
<action name="fabricCallback" class="com.xxx.FabricCallbackAction">
<interceptor-ref name="fabricStack"/>
<result type="json">
<param name="root">data</param>
</result>
</action>
步骤五:FabricCallbackAction 里用 @Autowired 注入真正的 Service,完成业务落库,最后把执行结果 hash 写回 Fabric,形成 “链上-链下-链上” 闭环。
拓展思考
- 如果 Fabric 区块高度增长过快,Struts 线程池出现 队列积压,你会如何用 Sentinel 限流 保护下游 MySQL?
- 当事件回调需要 人工复核 时,怎样把复核流程也建模成 Struts 的 工作流拦截器,同时满足 国密 SM2 签名 要求?
- 在 省政务云 的 双活数据中心 场景下,如何让 Struts 应用 幂等地 消费同一个 Fabric 事件,避免重复入账?