flow - 拦截器(FlowInterceptor)
2026年1月13日 下午9:00:09
拦截器通过环绕(Around)流程执行过程,为您提供了强大的切面扩展能力。您可以利用它进行执行耗时统计、全局异常捕获、上下文参数预处理等操作。
FlowInterceptor 提供了三个关键的切入点:
- doIntercept:环绕整个流程执行过程。
- onNodeStart:在每个节点任务开始前触发。
- onNodeEnd:在每个节点任务结束后触发。
常见使用场景:
| 场景 | 实现建议 |
|---|---|
| 性能监控 | 在 doIntercept 中使用 System.currentTimeMillis() 统计总耗时。 |
| 执行审计 | 在 onNodeStart 中记录节点 ID 和当前上下文参数到数据库。 |
| 安全校验 | 在 doIntercept 中校验 FlowContext 是否携带必要的 Token。 |
| 参数补全 | 在流程开始前,通过拦截器向 FlowContext 注入全局配置。 |
1、使用示例
组件注解模式
import org.noear.solon.annotation.Component;
import org.noear.solon.flow.intercept.FlowInterceptor;
import org.noear.solon.flow.intercept.FlowInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component
public class FlowInterceptorImpl implements FlowInterceptor {
static Logger log = LoggerFactory.getLogger(ChainInterceptorImpl.class);
@Override
public void doIntercept(FlowInvocation inv) throws Throwable {
long start = System.currentTimeMillis();
try {
inv.invoke();
} catch (Throwable ex) {
log.error("Graph eval failure: " + inv.getStartNode().getGraph().getId(), ex);
} finally {
long end = System.currentTimeMillis();
System.out.println(end - start);
}
}
}
原生 java 模式:
flowEngine.addInterceptor(new FlowInterceptorImpl());
2、FlowInterceptor 接口参考
public interface FlowInterceptor {
/**
* 拦截执行
*
* @param invocation 调用者
*/
void doIntercept(FlowInvocation invocation) throws FlowException;
/**
* 节点运行开始时
*
* @since 3.4
*/
default void onNodeStart(FlowContext context, Node node) {
}
/**
* 节点运行结束时
*
* @since 3.4
*/
default void onNodeEnd(FlowContext context, Node node) {
}
}