执行流程
概述
责任链的执行流程是框架的核心机制,它定义了请求如何在处理器链中传递、处理和响应。一个设计良好的执行流程应该具备清晰的生命周期、完善的错误处理和高效的性能表现。本章将详细介绍责任链的执行流程设计与实现。
执行流程概览
1. 整体执行流程
sequenceDiagram
participant Client as 客户端
participant Executor as 链执行器
participant Handler1 as 处理器1
participant Handler2 as 处理器2
participant Handler3 as 处理器3
participant Context as 上下文
Client->>Executor: execute(chainId, context)
Executor->>Context: 初始化上下文
Executor->>Handler1: handle(context)
Handler1->>Handler1: onBefore(context)
Handler1->>Handler1: shouldSkip(context)?
alt 不跳过
Handler1->>Handler1: doHandle(context)
Handler1->>Handler1: onAfter(context)
Handler1->>Handler2: handle(context)
Handler2->>Handler2: onBefore(context)
Handler2->>Handler2: shouldSkip(context)?
alt 不跳过
Handler2->>Handler2: doHandle(context)
Handler2->>Handler2: onAfter(context)
Handler2->>Handler3: handle(context)
Handler3->>Handler3: onBefore(context)
Handler3->>Handler3: doHandle(context)
Handler3->>Handler3: onAfter(context)
Handler3-->>Handler2: return true
else 跳过
Handler2->>Handler3: handle(context)
end
Handler2-->>Handler1: return true
else 跳过
Handler1->>Handler2: handle(context)
end
Handler1-->>Executor: return result
Executor-->>Client: return response
2. 执行状态机
stateDiagram-v2
[*] --> Initialized: 创建上下文
Initialized --> Processing: 开始处理
Processing --> BeforeHook: 执行前置钩子
BeforeHook --> SkipCheck: 检查是否跳过
SkipCheck --> DoHandle: 不跳过
SkipCheck --> NextHandler: 跳过当前处理器
DoHandle --> AfterHook: 处理完成
AfterHook --> ContinueCheck: 检查是否继续
ContinueCheck --> NextHandler: 继续传递
ContinueCheck --> Completed: 中断链路
NextHandler --> Processing: 有下一个处理器
NextHandler --> Completed: 无下一个处理器
Processing --> ErrorHook: 处理异常
ErrorHook --> Failed: 异常处理完成
Completed --> [*]
Failed --> [*]
链执行器实现
1. 基础执行器
java
/**
* 责任链执行器
* 负责管理和执行责任链
* @param <T> 请求类型
* @param <R> 响应类型
*/
public class ChainExecutor<T, R> {
private static final Logger logger = LoggerFactory.getLogger(ChainExecutor.class);
private final ChainRegistry<T, R> chainRegistry;
private final ExecutorService executorService;
private final ChainMetrics metrics;
public ChainExecutor(ChainRegistry<T, R> chainRegistry) {
this.chainRegistry = chainRegistry;
this.executorService = Executors.newFixedThreadPool(10);
this.metrics = new ChainMetrics();
}
public ChainExecutor(ChainRegistry<T, R> chainRegistry, ExecutorService executorService) {
this.chainRegistry = chainRegistry;
this.executorService = executorService;
this.metrics = new ChainMetrics();
}
/**
* 同步执行责任链
* @param chainId 链标识
* @param context 执行上下文
* @return 执行结果
* @throws ChainExecutionException 执行异常
*/
public R execute(String chainId, Context<T, R> context) throws ChainExecutionException {
long startTime = System.currentTimeMillis();
String executionId = generateExecutionId();
try {
logger.info("Starting chain execution: chainId={}, executionId={}", chainId, executionId);
// 1. 获取责任链
Handler chain = chainRegistry.getChain(chainId);
if (chain == null) {
throw new ChainNotFoundException("Chain not found: " + chainId);
}
// 2. 设置执行上下文
setupExecutionContext(context, chainId, executionId);
// 3. 执行责任链
boolean result = executeChain(chain, context);
// 4. 处理执行结果
R response = handleExecutionResult(context, result);
// 5. 记录成功指标
long duration = System.currentTimeMillis() - startTime;
metrics.recordSuccess(chainId, duration);
logger.info("Chain execution completed: chainId={}, executionId={}, duration={}ms",
chainId, executionId, duration);
return response;
} catch (Exception e) {
// 记录失败指标
long duration = System.currentTimeMillis() - startTime;
metrics.recordFailure(chainId, duration, e);
logger.error("Chain execution failed: chainId={}, executionId={}", chainId, executionId, e);
if (e instanceof ChainExecutionException) {
throw e;
} else {
throw new ChainExecutionException("Chain execution failed", e);
}
}
}
/**
* 异步执行责任链
* @param chainId 链标识
* @param context 执行上下文
* @return 异步执行结果
*/
public CompletableFuture<R> executeAsync(String chainId, Context<T, R> context) {
return CompletableFuture.supplyAsync(() -> {
try {
return execute(chainId, context);
} catch (ChainExecutionException e) {
throw new CompletionException(e);
}
}, executorService);
}
/**
* 执行责任链核心逻辑
*/
private boolean executeChain(Handler chain, Context<T, R> context) {
try {
return chain.handle(context);
} catch (Exception e) {
logger.error("Unexpected error during chain execution", e);
throw new ChainExecutionException("Unexpected error during chain execution", e);
}
}
/**
* 设置执行上下文
*/
private void setupExecutionContext(Context<T, R> context, String chainId, String executionId) {
context.setAttribute("chainId", chainId);
context.setAttribute("executionId", executionId);
context.setAttribute("startTime", System.currentTimeMillis());
context.setAttribute("threadName", Thread.currentThread().getName());
}
/**
* 处理执行结果
*/
private R handleExecutionResult(Context<T, R> context, boolean result) {
R response = context.getResponse();
if (response == null) {
logger.warn("No response set in context, creating default response");
response = createDefaultResponse(result);
}
return response;
}
/**
* 创建默认响应
*/
@SuppressWarnings("unchecked")
private R createDefaultResponse(boolean success) {
// 这里需要根据具体的响应类型来实现
// 简化实现,实际项目中应该有更完善的默认响应创建逻辑
return (R) new DefaultResponse(success);
}
/**
* 生成执行ID
*/
private String generateExecutionId() {
return UUID.randomUUID().toString().replace("-", "").substring(0, 8);
}
/**
* 关闭执行器
*/
public void shutdown() {
executorService.shutdown();
try {
if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
executorService.shutdownNow();
}
} catch (InterruptedException e) {
executorService.shutdownNow();
Thread.currentThread().interrupt();
}
}
}
2. 高级执行器
java
/**
* 高级责任链执行器
* 提供更多高级功能,如重试、超时、熔断等
*/
public class AdvancedChainExecutor<T, R> extends ChainExecutor<T, R> {
private final RetryPolicy retryPolicy;
private final CircuitBreaker circuitBreaker;
private final long timeoutMillis;
public AdvancedChainExecutor(ChainRegistry<T, R> chainRegistry,
ExecutorService executorService,
RetryPolicy retryPolicy,
CircuitBreaker circuitBreaker,
long timeoutMillis) {
super(chainRegistry, executorService);
this.retryPolicy = retryPolicy;
this.circuitBreaker = circuitBreaker;
this.timeoutMillis = timeoutMillis;
}
@Override
public R execute(String chainId, Context<T, R> context) throws ChainExecutionException {
// 检查熔断器状态
if (circuitBreaker != null && circuitBreaker.isOpen()) {
throw new ChainExecutionException("Circuit breaker is open for chain: " + chainId);
}
// 执行重试逻辑
return executeWithRetry(chainId, context);
}
@Override
public CompletableFuture<R> executeAsync(String chainId, Context<T, R> context) {
CompletableFuture<R> future = super.executeAsync(chainId, context);
// 添加超时控制
if (timeoutMillis > 0) {
future = future.orTimeout(timeoutMillis, TimeUnit.MILLISECONDS);
}
return future;
}
/**
* 带重试的执行
*/
private R executeWithRetry(String chainId, Context<T, R> context) {
int attempts = 0;
Exception lastException = null;
while (attempts < retryPolicy.getMaxAttempts()) {
try {
attempts++;
if (attempts > 1) {
logger.info("Retrying chain execution: chainId={}, attempt={}", chainId, attempts);
// 重试延迟
long delay = retryPolicy.getDelay(attempts - 1);
if (delay > 0) {
Thread.sleep(delay);
}
}
R result = super.execute(chainId, context);
// 执行成功,记录熔断器成功
if (circuitBreaker != null) {
circuitBreaker.recordSuccess();
}
return result;
} catch (Exception e) {
lastException = e;
// 记录熔断器失败
if (circuitBreaker != null) {
circuitBreaker.recordFailure();
}
// 检查是否应该重试
if (!retryPolicy.shouldRetry(e) || attempts >= retryPolicy.getMaxAttempts()) {
break;
}
logger.warn("Chain execution failed, will retry: chainId={}, attempt={}, error={}",
chainId, attempts, e.getMessage());
}
}
throw new ChainExecutionException(
String.format("Chain execution failed after %d attempts", attempts), lastException);
}
}
执行生命周期
1. 生命周期钩子
java
/**
* 执行生命周期监听器
*/
public interface ExecutionLifecycleListener {
/**
* 执行开始前
*/
default void beforeExecution(String chainId, Context context) {
// 默认空实现
}
/**
* 执行完成后
*/
default void afterExecution(String chainId, Context context, Object result) {
// 默认空实现
}
/**
* 执行异常时
*/
default void onExecutionError(String chainId, Context context, Exception error) {
// 默认空实现
}
/**
* 处理器执行前
*/
default void beforeHandler(Handler handler, Context context) {
// 默认空实现
}
/**
* 处理器执行后
*/
default void afterHandler(Handler handler, Context context, boolean result) {
// 默认空实现
}
/**
* 处理器异常时
*/
default void onHandlerError(Handler handler, Context context, Exception error) {
// 默认空实现
}
}
/**
* 日志记录监听器
*/
public class LoggingExecutionListener implements ExecutionLifecycleListener {
private static final Logger logger = LoggerFactory.getLogger(LoggingExecutionListener.class);
@Override
public void beforeExecution(String chainId, Context context) {
logger.info("Starting chain execution: chainId={}, request={}",
chainId, context.getRequest());
}
@Override
public void afterExecution(String chainId, Context context, Object result) {
Long startTime = context.getAttribute("startTime", Long.class);
long duration = startTime != null ? System.currentTimeMillis() - startTime : 0;
logger.info("Chain execution completed: chainId={}, duration={}ms, response={}",
chainId, duration, context.getResponse());
}
@Override
public void onExecutionError(String chainId, Context context, Exception error) {
logger.error("Chain execution failed: chainId={}, error={}",
chainId, error.getMessage(), error);
}
@Override
public void beforeHandler(Handler handler, Context context) {
logger.debug("Executing handler: {}", handler.getClass().getSimpleName());
}
@Override
public void afterHandler(Handler handler, Context context, boolean result) {
logger.debug("Handler completed: {}, result={}",
handler.getClass().getSimpleName(), result);
}
@Override
public void onHandlerError(Handler handler, Context context, Exception error) {
logger.error("Handler execution failed: {}, error={}",
handler.getClass().getSimpleName(), error.getMessage(), error);
}
}
2. 性能监控监听器
java
/**
* 性能监控监听器
*/
public class MetricsExecutionListener implements ExecutionLifecycleListener {
private final MeterRegistry meterRegistry;
private final Timer.Builder chainTimerBuilder;
private final Timer.Builder handlerTimerBuilder;
private final Counter.Builder successCounterBuilder;
private final Counter.Builder errorCounterBuilder;
public MetricsExecutionListener(MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;
this.chainTimerBuilder = Timer.builder("chain.execution.duration")
.description("Chain execution duration");
this.handlerTimerBuilder = Timer.builder("handler.execution.duration")
.description("Handler execution duration");
this.successCounterBuilder = Counter.builder("chain.execution.success")
.description("Successful chain executions");
this.errorCounterBuilder = Counter.builder("chain.execution.error")
.description("Failed chain executions");
}
@Override
public void beforeExecution(String chainId, Context context) {
context.setAttribute("execution.start.time", System.nanoTime());
}
@Override
public void afterExecution(String chainId, Context context, Object result) {
Long startTime = context.getAttribute("execution.start.time", Long.class);
if (startTime != null) {
long duration = System.nanoTime() - startTime;
chainTimerBuilder.tag("chainId", chainId)
.tag("status", "success")
.register(meterRegistry)
.record(duration, TimeUnit.NANOSECONDS);
}
successCounterBuilder.tag("chainId", chainId)
.register(meterRegistry)
.increment();
}
@Override
public void onExecutionError(String chainId, Context context, Exception error) {
Long startTime = context.getAttribute("execution.start.time", Long.class);
if (startTime != null) {
long duration = System.nanoTime() - startTime;
chainTimerBuilder.tag("chainId", chainId)
.tag("status", "error")
.register(meterRegistry)
.record(duration, TimeUnit.NANOSECONDS);
}
errorCounterBuilder.tag("chainId", chainId)
.tag("errorType", error.getClass().getSimpleName())
.register(meterRegistry)
.increment();
}
@Override
public void beforeHandler(Handler handler, Context context) {
String handlerKey = "handler." + handler.getClass().getSimpleName() + ".start.time";
context.setAttribute(handlerKey, System.nanoTime());
}
@Override
public void afterHandler(Handler handler, Context context, boolean result) {
String handlerKey = "handler." + handler.getClass().getSimpleName() + ".start.time";
Long startTime = context.getAttribute(handlerKey, Long.class);
if (startTime != null) {
long duration = System.nanoTime() - startTime;
handlerTimerBuilder.tag("handlerType", handler.getClass().getSimpleName())
.tag("result", String.valueOf(result))
.register(meterRegistry)
.record(duration, TimeUnit.NANOSECONDS);
}
}
}
错误处理机制
1. 异常分类
java
/**
* 责任链异常基类
*/
public abstract class ChainException extends Exception {
private final String chainId;
private final String executionId;
public ChainException(String message, String chainId, String executionId) {
super(message);
this.chainId = chainId;
this.executionId = executionId;
}
public ChainException(String message, Throwable cause, String chainId, String executionId) {
super(message, cause);
this.chainId = chainId;
this.executionId = executionId;
}
public String getChainId() {
return chainId;
}
public String getExecutionId() {
return executionId;
}
}
/**
* 链执行异常
*/
public class ChainExecutionException extends ChainException {
public ChainExecutionException(String message, String chainId, String executionId) {
super(message, chainId, executionId);
}
public ChainExecutionException(String message, Throwable cause, String chainId, String executionId) {
super(message, cause, chainId, executionId);
}
}
/**
* 链未找到异常
*/
public class ChainNotFoundException extends ChainException {
public ChainNotFoundException(String chainId) {
super("Chain not found: " + chainId, chainId, null);
}
}
/**
* 处理器执行异常
*/
public class HandlerExecutionException extends ChainException {
private final String handlerName;
public HandlerExecutionException(String message, String handlerName, String chainId, String executionId) {
super(message, chainId, executionId);
this.handlerName = handlerName;
}
public HandlerExecutionException(String message, Throwable cause, String handlerName, String chainId, String executionId) {
super(message, cause, chainId, executionId);
this.handlerName = handlerName;
}
public String getHandlerName() {
return handlerName;
}
}
2. 错误恢复策略
java
/**
* 错误恢复策略接口
*/
public interface ErrorRecoveryStrategy {
/**
* 尝试恢复错误
* @param context 执行上下文
* @param error 发生的错误
* @return 是否成功恢复
*/
boolean recover(Context context, Exception error);
/**
* 判断是否可以恢复该类型的错误
* @param error 错误
* @return 是否可以恢复
*/
boolean canRecover(Exception error);
}
/**
* 默认错误恢复策略
*/
public class DefaultErrorRecoveryStrategy implements ErrorRecoveryStrategy {
private static final Logger logger = LoggerFactory.getLogger(DefaultErrorRecoveryStrategy.class);
@Override
public boolean recover(Context context, Exception error) {
if (error instanceof ValidationException) {
// 验证异常恢复:设置默认值
return recoverFromValidationError(context, (ValidationException) error);
} else if (error instanceof TimeoutException) {
// 超时异常恢复:重试或降级
return recoverFromTimeoutError(context, (TimeoutException) error);
} else if (error instanceof BusinessException) {
// 业务异常恢复:设置错误响应
return recoverFromBusinessError(context, (BusinessException) error);
}
return false;
}
@Override
public boolean canRecover(Exception error) {
return error instanceof ValidationException ||
error instanceof TimeoutException ||
error instanceof BusinessException;
}
private boolean recoverFromValidationError(Context context, ValidationException error) {
logger.warn("Recovering from validation error: {}", error.getMessage());
// 设置默认响应
Object defaultResponse = createDefaultResponse("Validation failed: " + error.getMessage());
context.setResponse(defaultResponse);
return true;
}
private boolean recoverFromTimeoutError(Context context, TimeoutException error) {
logger.warn("Recovering from timeout error: {}", error.getMessage());
// 设置超时响应
Object timeoutResponse = createDefaultResponse("Request timeout");
context.setResponse(timeoutResponse);
return true;
}
private boolean recoverFromBusinessError(Context context, BusinessException error) {
logger.warn("Recovering from business error: {}", error.getMessage());
// 设置业务错误响应
Object errorResponse = createErrorResponse(error.getErrorCode(), error.getMessage());
context.setResponse(errorResponse);
return true;
}
private Object createDefaultResponse(String message) {
// 创建默认响应对象
return new DefaultResponse(false, message);
}
private Object createErrorResponse(String errorCode, String message) {
// 创建错误响应对象
return new ErrorResponse(errorCode, message);
}
}
性能优化
1. 执行器池化
java
/**
* 执行器池
*/
public class ChainExecutorPool {
private final ObjectPool<ChainExecutor> executorPool;
private final ChainRegistry chainRegistry;
private final ExecutorService executorService;
public ChainExecutorPool(ChainRegistry chainRegistry, int poolSize) {
this.chainRegistry = chainRegistry;
this.executorService = Executors.newFixedThreadPool(poolSize);
GenericObjectPoolConfig<ChainExecutor> config = new GenericObjectPoolConfig<>();
config.setMaxTotal(poolSize);
config.setMaxIdle(poolSize / 2);
config.setMinIdle(1);
this.executorPool = new GenericObjectPool<>(
new ChainExecutorFactory(chainRegistry, executorService), config);
}
/**
* 借用执行器
*/
public ChainExecutor borrowExecutor() throws Exception {
return executorPool.borrowObject();
}
/**
* 归还执行器
*/
public void returnExecutor(ChainExecutor executor) {
try {
executorPool.returnObject(executor);
} catch (Exception e) {
logger.warn("Failed to return executor to pool", e);
}
}
/**
* 使用执行器执行任务
*/
public <T, R> R execute(String chainId, Context<T, R> context,
Function<ChainExecutor<T, R>, R> task) {
ChainExecutor<T, R> executor = null;
try {
executor = borrowExecutor();
return task.apply(executor);
} catch (Exception e) {
throw new ChainExecutionException("Execution failed", e);
} finally {
if (executor != null) {
returnExecutor(executor);
}
}
}
/**
* 关闭池
*/
public void shutdown() {
executorPool.close();
executorService.shutdown();
}
}
2. 上下文复用
java
/**
* 上下文池
*/
public class ContextPool<T, R> {
private final Queue<Context<T, R>> contextQueue;
private final int maxSize;
public ContextPool(int maxSize) {
this.maxSize = maxSize;
this.contextQueue = new ConcurrentLinkedQueue<>();
}
/**
* 获取上下文
*/
public Context<T, R> acquire(T request) {
Context<T, R> context = contextQueue.poll();
if (context == null) {
context = new DefaultContext<>(request);
} else {
// 重置上下文
context.setRequest(request);
context.setResponse(null);
context.clearAttributes();
}
return context;
}
/**
* 释放上下文
*/
public void release(Context<T, R> context) {
if (contextQueue.size() < maxSize) {
// 清理敏感数据
context.clearAttributes();
contextQueue.offer(context);
}
}
}
监控和诊断
1. 执行追踪
java
/**
* 执行追踪器
*/
public class ExecutionTracer {
private final ThreadLocal<ExecutionTrace> currentTrace = new ThreadLocal<>();
/**
* 开始追踪
*/
public void startTrace(String chainId, String executionId) {
ExecutionTrace trace = new ExecutionTrace(chainId, executionId);
currentTrace.set(trace);
}
/**
* 记录处理器执行
*/
public void recordHandler(String handlerName, long startTime, long endTime, boolean success) {
ExecutionTrace trace = currentTrace.get();
if (trace != null) {
trace.addHandlerExecution(handlerName, startTime, endTime, success);
}
}
/**
* 结束追踪
*/
public ExecutionTrace endTrace() {
ExecutionTrace trace = currentTrace.get();
if (trace != null) {
trace.setEndTime(System.currentTimeMillis());
currentTrace.remove();
}
return trace;
}
/**
* 获取当前追踪
*/
public ExecutionTrace getCurrentTrace() {
return currentTrace.get();
}
}
/**
* 执行追踪信息
*/
public class ExecutionTrace {
private final String chainId;
private final String executionId;
private final long startTime;
private long endTime;
private final List<HandlerExecution> handlerExecutions;
public ExecutionTrace(String chainId, String executionId) {
this.chainId = chainId;
this.executionId = executionId;
this.startTime = System.currentTimeMillis();
this.handlerExecutions = new ArrayList<>();
}
public void addHandlerExecution(String handlerName, long startTime, long endTime, boolean success) {
handlerExecutions.add(new HandlerExecution(handlerName, startTime, endTime, success));
}
public long getTotalDuration() {
return endTime - startTime;
}
public long getHandlersDuration() {
return handlerExecutions.stream()
.mapToLong(HandlerExecution::getDuration)
.sum();
}
// getters and setters
}
/**
* 处理器执行信息
*/
public class HandlerExecution {
private final String handlerName;
private final long startTime;
private final long endTime;
private final boolean success;
public HandlerExecution(String handlerName, long startTime, long endTime, boolean success) {
this.handlerName = handlerName;
this.startTime = startTime;
this.endTime = endTime;
this.success = success;
}
public long getDuration() {
return endTime - startTime;
}
// getters
}
总结
责任链的执行流程是框架的核心,包含以下关键要素:
- 清晰的生命周期:从初始化到完成的完整流程
- 完善的错误处理:异常分类、恢复策略、错误传播
- 性能优化:池化、复用、异步执行
- 监控诊断:指标收集、执行追踪、问题定位
- 扩展机制:生命周期钩子、监听器、插件
通过合理的执行流程设计,我们可以构建出既高效又可靠的责任链框架。在下一章中,我们将介绍责任链框架的高级应用场景。