手搓责任链框架 6:高级应用

高级应用

概述

责任链框架的高级应用涵盖了过滤器链、中断处理机制、性能优化等多个方面。这些高级特性使得框架能够应对复杂的业务场景,提供更强大的功能和更好的性能表现。本章将详细介绍这些高级应用的设计与实现。

过滤器链实现

1. Web过滤器链

graph LR A[HTTP请求] --> B[CORS过滤器] B --> C[认证过滤器] C --> D[授权过滤器] D --> E[限流过滤器] E --> F[日志过滤器] F --> G[业务处理器] G --> H[HTTP响应] B -.->|OPTIONS请求| H C -.->|认证失败| H D -.->|权限不足| H E -.->|超出限制| H
java 复制代码
/**
 * Web过滤器链实现
 */
public class WebFilterChain {
    
    private final ChainExecutor<HttpRequest, HttpResponse> executor;
    
    public WebFilterChain() {
        this.executor = buildFilterChain();
    }
    
    /**
     * 构建Web过滤器链
     */
    private ChainExecutor<HttpRequest, HttpResponse> buildFilterChain() {
        ChainRegistry<HttpRequest, HttpResponse> registry = new ChainRegistry<>();
        
        // 构建过滤器链
        Handler chain = new AdvancedChainBuilder<HttpRequest, HttpResponse>()
            .addHandler(new CorsFilter())
            .addHandler(new AuthenticationFilter())
            .addHandler(new AuthorizationFilter())
            .addHandler(new RateLimitFilter())
            .addHandler(new LoggingFilter())
            .addHandler(new BusinessHandler())
            .build();
        
        registry.registerChain("web-filter", chain);
        return new ChainExecutor<>(registry);
    }
    
    /**
     * 处理HTTP请求
     */
    public HttpResponse doFilter(HttpRequest request) {
        Context<HttpRequest, HttpResponse> context = new DefaultContext<>(request);
        
        try {
            return executor.execute("web-filter", context);
        } catch (ChainExecutionException e) {
            return createErrorResponse(e);
        }
    }
    
    private HttpResponse createErrorResponse(ChainExecutionException e) {
        return HttpResponse.builder()
            .status(500)
            .body("Internal Server Error: " + e.getMessage())
            .build();
    }
}

/**
 * CORS过滤器
 */
public class CorsFilter extends AbstractHandler<HttpRequest, HttpResponse> {
    
    @Override
    protected boolean doHandle(Context<HttpRequest, HttpResponse> context) {
        HttpRequest request = context.getRequest();
        
        // 处理预检请求
        if ("OPTIONS".equals(request.getMethod())) {
            HttpResponse response = HttpResponse.builder()
                .status(200)
                .header("Access-Control-Allow-Origin", "*")
                .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
                .header("Access-Control-Allow-Headers", "Content-Type, Authorization")
                .build();
            
            context.setResponse(response);
            return false; // 预检请求直接返回,不继续处理
        }
        
        // 设置CORS头
        context.setAttribute("cors.origin", "*");
        context.setAttribute("cors.methods", "GET, POST, PUT, DELETE");
        
        return true;
    }
}

/**
 * 限流过滤器
 */
public class RateLimitFilter extends AbstractHandler<HttpRequest, HttpResponse> {
    
    private final RateLimiter rateLimiter;
    
    public RateLimitFilter() {
        this.rateLimiter = RateLimiter.create(100.0); // 每秒100个请求
    }
    
    @Override
    protected boolean doHandle(Context<HttpRequest, HttpResponse> context) {
        if (!rateLimiter.tryAcquire()) {
            HttpResponse response = HttpResponse.builder()
                .status(429)
                .body("Too Many Requests")
                .build();
            
            context.setResponse(response);
            return false; // 限流,直接返回
        }
        
        return true;
    }
}

2. 数据处理管道

java 复制代码
/**
 * 数据处理管道
 */
public class DataProcessingPipeline {
    
    private final ChainExecutor<DataPacket, ProcessingResult> executor;
    
    public DataProcessingPipeline() {
        this.executor = buildPipeline();
    }
    
    /**
     * 构建数据处理管道
     */
    private ChainExecutor<DataPacket, ProcessingResult> buildPipeline() {
        ChainRegistry<DataPacket, ProcessingResult> registry = new ChainRegistry<>();
        
        Handler chain = new AdvancedChainBuilder<DataPacket, ProcessingResult>()
            .addHandler(new DataValidationProcessor())
            .addHandler(new DataTransformationProcessor())
            .addHandler(new DataEnrichmentProcessor())
            .addHandler(new DataPersistenceProcessor())
            .addHandler(new DataNotificationProcessor())
            .build();
        
        registry.registerChain("data-processing", chain);
        return new ChainExecutor<>(registry);
    }
    
    /**
     * 处理数据包
     */
    public ProcessingResult process(DataPacket dataPacket) {
        Context<DataPacket, ProcessingResult> context = new DefaultContext<>(dataPacket);
        
        try {
            return executor.execute("data-processing", context);
        } catch (ChainExecutionException e) {
            return ProcessingResult.failure(e.getMessage());
        }
    }
}

/**
 * 数据验证处理器
 */
public class DataValidationProcessor extends AbstractHandler<DataPacket, ProcessingResult> {
    
    @Override
    protected boolean doHandle(Context<DataPacket, ProcessingResult> context) {
        DataPacket packet = context.getRequest();
        
        // 数据格式验证
        if (!isValidFormat(packet)) {
            context.setResponse(ProcessingResult.failure("Invalid data format"));
            return false;
        }
        
        // 数据完整性验证
        if (!isDataComplete(packet)) {
            context.setResponse(ProcessingResult.failure("Incomplete data"));
            return false;
        }
        
        // 业务规则验证
        if (!isBusinessRuleValid(packet)) {
            context.setResponse(ProcessingResult.failure("Business rule validation failed"));
            return false;
        }
        
        context.setAttribute("validation.passed", true);
        return true;
    }
    
    private boolean isValidFormat(DataPacket packet) {
        // 实现数据格式验证逻辑
        return packet.getData() != null && !packet.getData().isEmpty();
    }
    
    private boolean isDataComplete(DataPacket packet) {
        // 实现数据完整性验证逻辑
        return packet.getHeaders() != null && packet.getTimestamp() != null;
    }
    
    private boolean isBusinessRuleValid(DataPacket packet) {
        // 实现业务规则验证逻辑
        return true;
    }
}

/**
 * 数据转换处理器
 */
public class DataTransformationProcessor extends AbstractHandler<DataPacket, ProcessingResult> {
    
    @Override
    protected boolean doHandle(Context<DataPacket, ProcessingResult> context) {
        DataPacket packet = context.getRequest();
        
        try {
            // 数据格式转换
            String transformedData = transformDataFormat(packet.getData());
            
            // 数据标准化
            String normalizedData = normalizeData(transformedData);
            
            // 数据清洗
            String cleanedData = cleanData(normalizedData);
            
            // 更新数据包
            packet.setData(cleanedData);
            context.setAttribute("transformation.completed", true);
            
            return true;
        } catch (Exception e) {
            context.setResponse(ProcessingResult.failure("Data transformation failed: " + e.getMessage()));
            return false;
        }
    }
    
    private String transformDataFormat(String data) {
        // 实现数据格式转换逻辑
        return data.toUpperCase();
    }
    
    private String normalizeData(String data) {
        // 实现数据标准化逻辑
        return data.trim();
    }
    
    private String cleanData(String data) {
        // 实现数据清洗逻辑
        return data.replaceAll("[^a-zA-Z0-9\\s]", "");
    }
}

中断处理机制

1. 优雅中断

java 复制代码
/**
 * 可中断的责任链执行器
 */
public class InterruptibleChainExecutor<T, R> extends ChainExecutor<T, R> {
    
    private final AtomicBoolean interrupted = new AtomicBoolean(false);
    private final Map<String, CompletableFuture<R>> runningExecutions = new ConcurrentHashMap<>();
    
    public InterruptibleChainExecutor(ChainRegistry<T, R> chainRegistry) {
        super(chainRegistry);
    }
    
    @Override
    public R execute(String chainId, Context<T, R> context) throws ChainExecutionException {
        String executionId = generateExecutionId();
        
        try {
            // 检查是否已被中断
            checkInterrupted();
            
            // 注册执行
            CompletableFuture<R> future = CompletableFuture.supplyAsync(() -> {
                try {
                    return super.execute(chainId, context);
                } catch (ChainExecutionException e) {
                    throw new CompletionException(e);
                }
            });
            
            runningExecutions.put(executionId, future);
            
            // 等待执行完成或中断
            return future.get();
            
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new ChainExecutionException("Chain execution interrupted", e);
        } catch (ExecutionException e) {
            if (e.getCause() instanceof ChainExecutionException) {
                throw (ChainExecutionException) e.getCause();
            } else {
                throw new ChainExecutionException("Chain execution failed", e.getCause());
            }
        } finally {
            runningExecutions.remove(executionId);
        }
    }
    
    /**
     * 中断所有正在执行的链
     */
    public void interrupt() {
        interrupted.set(true);
        
        // 取消所有正在执行的任务
        runningExecutions.values().forEach(future -> future.cancel(true));
        runningExecutions.clear();
    }
    
    /**
     * 检查是否被中断
     */
    private void checkInterrupted() throws ChainExecutionException {
        if (interrupted.get() || Thread.currentThread().isInterrupted()) {
            throw new ChainExecutionException("Chain execution interrupted");
        }
    }
    
    /**
     * 重置中断状态
     */
    public void resetInterrupt() {
        interrupted.set(false);
    }
}

/**
 * 可中断的处理器基类
 */
public abstract class InterruptibleHandler<T, R> extends AbstractHandler<T, R> {
    
    @Override
    protected final boolean doHandle(Context<T, R> context) {
        try {
            // 检查中断状态
            checkInterrupted();
            
            // 执行具体处理逻辑
            return doInterruptibleHandle(context);
            
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new ChainExecutionException("Handler interrupted", e);
        }
    }
    
    /**
     * 可中断的处理逻辑
     */
    protected abstract boolean doInterruptibleHandle(Context<T, R> context) throws InterruptedException;
    
    /**
     * 检查中断状态
     */
    protected void checkInterrupted() throws InterruptedException {
        if (Thread.currentThread().isInterrupted()) {
            throw new InterruptedException("Handler execution interrupted");
        }
    }
}

2. 超时中断

java 复制代码
/**
 * 超时处理器装饰器
 */
public class TimeoutHandlerDecorator<T, R> implements Handler {
    
    private final Handler delegate;
    private final long timeoutMillis;
    private final ExecutorService executorService;
    
    public TimeoutHandlerDecorator(Handler delegate, long timeoutMillis) {
        this.delegate = delegate;
        this.timeoutMillis = timeoutMillis;
        this.executorService = Executors.newCachedThreadPool();
    }
    
    @Override
    public boolean handle(Context context) {
        CompletableFuture<Boolean> future = CompletableFuture.supplyAsync(
            () -> delegate.handle(context), executorService);
        
        try {
            return future.get(timeoutMillis, TimeUnit.MILLISECONDS);
        } catch (TimeoutException e) {
            future.cancel(true);
            throw new ChainExecutionException("Handler execution timeout", e);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            future.cancel(true);
            throw new ChainExecutionException("Handler execution interrupted", e);
        } catch (ExecutionException e) {
            throw new ChainExecutionException("Handler execution failed", e.getCause());
        }
    }
    
    @Override
    public void setNext(Handler handler) {
        delegate.setNext(handler);
    }
    
    @Override
    public Handler getNext() {
        return delegate.getNext();
    }
}

/**
 * 超时感知的链构建器
 */
public class TimeoutAwareChainBuilder<T, R> extends AdvancedChainBuilder<T, R> {
    
    private long defaultTimeoutMillis = 5000; // 默认5秒超时
    
    /**
     * 设置默认超时时间
     */
    public TimeoutAwareChainBuilder<T, R> setDefaultTimeout(long timeoutMillis) {
        this.defaultTimeoutMillis = timeoutMillis;
        return this;
    }
    
    /**
     * 添加带超时的处理器
     */
    public TimeoutAwareChainBuilder<T, R> addHandlerWithTimeout(Handler handler, long timeoutMillis) {
        Handler timeoutHandler = new TimeoutHandlerDecorator(handler, timeoutMillis);
        return (TimeoutAwareChainBuilder<T, R>) addHandler(timeoutHandler);
    }
    
    /**
     * 添加使用默认超时的处理器
     */
    @Override
    public ChainBuilder<T, R> addHandler(Handler handler) {
        return addHandlerWithTimeout(handler, defaultTimeoutMillis);
    }
}

性能优化建议

1. 内存优化

java 复制代码
/**
 * 内存优化的上下文实现
 */
public class MemoryOptimizedContext<T, R> implements Context<T, R> {
    
    private final T request;
    private R response;
    private Map<String, Object> attributes;
    
    public MemoryOptimizedContext(T request) {
        this.request = request;
        // 延迟初始化attributes,节省内存
    }
    
    @Override
    public void setAttribute(String key, Object value) {
        if (attributes == null) {
            attributes = new HashMap<>();
        }
        
        if (value == null) {
            attributes.remove(key);
            // 如果attributes为空,释放内存
            if (attributes.isEmpty()) {
                attributes = null;
            }
        } else {
            attributes.put(key, value);
        }
    }
    
    @Override
    public Object getAttribute(String key) {
        return attributes != null ? attributes.get(key) : null;
    }
    
    @Override
    public void clearAttributes() {
        if (attributes != null) {
            attributes.clear();
            attributes = null; // 释放内存
        }
    }
    
    // 其他方法实现...
}

/**
 * 轻量级处理器基类
 */
public abstract class LightweightHandler<T, R> implements Handler {
    
    private Handler nextHandler;
    
    @Override
    public final boolean handle(Context context) {
        try {
            boolean result = doHandle(context);
            
            if (result && nextHandler != null) {
                return nextHandler.handle(context);
            }
            
            return result;
        } catch (Exception e) {
            handleError(context, e);
            throw e;
        }
    }
    
    /**
     * 轻量级处理逻辑
     */
    protected abstract boolean doHandle(Context<T, R> context);
    
    /**
     * 简化的错误处理
     */
    protected void handleError(Context<T, R> context, Exception e) {
        // 默认空实现,减少内存占用
    }
    
    @Override
    public void setNext(Handler handler) {
        this.nextHandler = handler;
    }
    
    @Override
    public Handler getNext() {
        return nextHandler;
    }
}

2. 并发优化

java 复制代码
/**
 * 并发优化的链执行器
 */
public class ConcurrentChainExecutor<T, R> extends ChainExecutor<T, R> {
    
    private final ForkJoinPool forkJoinPool;
    private final int parallelismThreshold;
    
    public ConcurrentChainExecutor(ChainRegistry<T, R> chainRegistry, 
                                  int parallelism, 
                                  int parallelismThreshold) {
        super(chainRegistry);
        this.forkJoinPool = new ForkJoinPool(parallelism);
        this.parallelismThreshold = parallelismThreshold;
    }
    
    /**
     * 并行执行多个请求
     */
    public List<R> executeParallel(String chainId, List<Context<T, R>> contexts) {
        if (contexts.size() < parallelismThreshold) {
            // 请求数量较少,使用串行执行
            return contexts.stream()
                .map(context -> {
                    try {
                        return execute(chainId, context);
                    } catch (ChainExecutionException e) {
                        throw new RuntimeException(e);
                    }
                })
                .collect(Collectors.toList());
        } else {
            // 请求数量较多,使用并行执行
            return contexts.parallelStream()
                .map(context -> {
                    try {
                        return execute(chainId, context);
                    } catch (ChainExecutionException e) {
                        throw new RuntimeException(e);
                    }
                })
                .collect(Collectors.toList());
        }
    }
    
    /**
     * 异步批量执行
     */
    public CompletableFuture<List<R>> executeBatchAsync(String chainId, List<Context<T, R>> contexts) {
        List<CompletableFuture<R>> futures = contexts.stream()
            .map(context -> executeAsync(chainId, context))
            .collect(Collectors.toList());
        
        return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
            .thenApply(v -> futures.stream()
                .map(CompletableFuture::join)
                .collect(Collectors.toList()));
    }
    
    @Override
    public void shutdown() {
        super.shutdown();
        forkJoinPool.shutdown();
    }
}

/**
 * 无锁的链注册器
 */
public class LockFreeChainRegistry<T, R> implements ChainRegistry<T, R> {
    
    private final ConcurrentHashMap<String, Handler> chains = new ConcurrentHashMap<>();
    private final AtomicReference<Map<String, Handler>> chainsRef = new AtomicReference<>(new HashMap<>());
    
    @Override
    public void registerChain(String chainId, Handler chain) {
        chains.put(chainId, chain);
        
        // 更新不可变映射
        Map<String, Handler> currentChains = chainsRef.get();
        Map<String, Handler> newChains = new HashMap<>(currentChains);
        newChains.put(chainId, chain);
        chainsRef.set(Collections.unmodifiableMap(newChains));
    }
    
    @Override
    public Handler getChain(String chainId) {
        return chainsRef.get().get(chainId);
    }
    
    @Override
    public Set<String> getChainIds() {
        return chainsRef.get().keySet();
    }
}

3. 缓存优化

java 复制代码
/**
 * 缓存感知的链执行器
 */
public class CacheAwareChainExecutor<T, R> extends ChainExecutor<T, R> {
    
    private final Cache<String, R> responseCache;
    private final Function<Context<T, R>, String> cacheKeyGenerator;
    
    public CacheAwareChainExecutor(ChainRegistry<T, R> chainRegistry,
                                  Cache<String, R> responseCache,
                                  Function<Context<T, R>, String> cacheKeyGenerator) {
        super(chainRegistry);
        this.responseCache = responseCache;
        this.cacheKeyGenerator = cacheKeyGenerator;
    }
    
    @Override
    public R execute(String chainId, Context<T, R> context) throws ChainExecutionException {
        // 生成缓存键
        String cacheKey = generateCacheKey(chainId, context);
        
        // 尝试从缓存获取
        R cachedResponse = responseCache.getIfPresent(cacheKey);
        if (cachedResponse != null) {
            logger.debug("Cache hit for key: {}", cacheKey);
            return cachedResponse;
        }
        
        // 缓存未命中,执行链
        R response = super.execute(chainId, context);
        
        // 缓存响应
        if (response != null && isCacheable(context, response)) {
            responseCache.put(cacheKey, response);
            logger.debug("Cached response for key: {}", cacheKey);
        }
        
        return response;
    }
    
    private String generateCacheKey(String chainId, Context<T, R> context) {
        if (cacheKeyGenerator != null) {
            return cacheKeyGenerator.apply(context);
        } else {
            return chainId + ":" + context.getRequest().hashCode();
        }
    }
    
    private boolean isCacheable(Context<T, R> context, R response) {
        // 检查响应是否可缓存
        Boolean cacheable = context.getAttribute("cacheable", Boolean.class);
        return cacheable == null || cacheable;
    }
}

/**
 * 缓存处理器
 */
public class CacheHandler<T, R> extends AbstractHandler<T, R> {
    
    private final Cache<String, Object> cache;
    private final Function<T, String> keyGenerator;
    
    public CacheHandler(Cache<String, Object> cache, Function<T, String> keyGenerator) {
        this.cache = cache;
        this.keyGenerator = keyGenerator;
    }
    
    @Override
    protected boolean doHandle(Context<T, R> context) {
        T request = context.getRequest();
        String cacheKey = keyGenerator.apply(request);
        
        // 尝试从缓存获取
        Object cachedValue = cache.getIfPresent(cacheKey);
        if (cachedValue != null) {
            context.setAttribute("cached.value", cachedValue);
            context.setAttribute("cache.hit", true);
        } else {
            context.setAttribute("cache.hit", false);
        }
        
        return true;
    }
    
    @Override
    protected void onAfter(Context<T, R> context) {
        // 在处理完成后缓存结果
        Boolean cacheHit = context.getAttribute("cache.hit", Boolean.class);
        if (Boolean.FALSE.equals(cacheHit)) {
            Object valueToCache = context.getAttribute("cache.value");
            if (valueToCache != null) {
                String cacheKey = keyGenerator.apply(context.getRequest());
                cache.put(cacheKey, valueToCache);
            }
        }
    }
}

监控和诊断

1. 性能监控

java 复制代码
/**
 * 性能监控处理器
 */
public class PerformanceMonitoringHandler<T, R> extends AbstractHandler<T, R> {
    
    private final MeterRegistry meterRegistry;
    private final Timer.Sample sample;
    
    public PerformanceMonitoringHandler(MeterRegistry meterRegistry) {
        this.meterRegistry = meterRegistry;
        this.sample = Timer.start(meterRegistry);
    }
    
    @Override
    protected void onBefore(Context<T, R> context) {
        // 记录开始时间
        context.setAttribute("performance.start.time", System.nanoTime());
        
        // 增加请求计数
        Counter.builder("chain.requests")
            .tag("handler", this.getClass().getSimpleName())
            .register(meterRegistry)
            .increment();
    }
    
    @Override
    protected boolean doHandle(Context<T, R> context) {
        // 实际的业务逻辑
        return processRequest(context);
    }
    
    @Override
    protected void onAfter(Context<T, R> context) {
        // 记录执行时间
        Long startTime = context.getAttribute("performance.start.time", Long.class);
        if (startTime != null) {
            long duration = System.nanoTime() - startTime;
            
            Timer.builder("chain.handler.duration")
                .tag("handler", this.getClass().getSimpleName())
                .register(meterRegistry)
                .record(duration, TimeUnit.NANOSECONDS);
        }
        
        // 记录成功计数
        Counter.builder("chain.success")
            .tag("handler", this.getClass().getSimpleName())
            .register(meterRegistry)
            .increment();
    }
    
    @Override
    protected void onError(Context<T, R> context, Exception e) {
        // 记录错误计数
        Counter.builder("chain.errors")
            .tag("handler", this.getClass().getSimpleName())
            .tag("error.type", e.getClass().getSimpleName())
            .register(meterRegistry)
            .increment();
    }
    
    protected boolean processRequest(Context<T, R> context) {
        // 子类实现具体的业务逻辑
        return true;
    }
}

/**
 * 健康检查处理器
 */
public class HealthCheckHandler extends AbstractHandler<HealthCheckRequest, HealthCheckResponse> {
    
    private final List<HealthIndicator> healthIndicators;
    
    public HealthCheckHandler(List<HealthIndicator> healthIndicators) {
        this.healthIndicators = healthIndicators;
    }
    
    @Override
    protected boolean doHandle(Context<HealthCheckRequest, HealthCheckResponse> context) {
        Map<String, Health> healthDetails = new HashMap<>();
        boolean overallHealthy = true;
        
        for (HealthIndicator indicator : healthIndicators) {
            try {
                Health health = indicator.health();
                healthDetails.put(indicator.getName(), health);
                
                if (health.getStatus() != Health.Status.UP) {
                    overallHealthy = false;
                }
            } catch (Exception e) {
                Health errorHealth = Health.down()
                    .withDetail("error", e.getMessage())
                    .build();
                healthDetails.put(indicator.getName(), errorHealth);
                overallHealthy = false;
            }
        }
        
        HealthCheckResponse response = HealthCheckResponse.builder()
            .status(overallHealthy ? "UP" : "DOWN")
            .details(healthDetails)
            .timestamp(Instant.now())
            .build();
        
        context.setResponse(response);
        return true;
    }
}

2. 分布式追踪

java 复制代码
/**
 * 分布式追踪处理器
 */
public class TracingHandler<T, R> extends AbstractHandler<T, R> {
    
    private final Tracer tracer;
    
    public TracingHandler(Tracer tracer) {
        this.tracer = tracer;
    }
    
    @Override
    protected boolean doHandle(Context<T, R> context) {
        Span span = tracer.nextSpan()
            .name("chain.handler." + this.getClass().getSimpleName())
            .tag("handler.type", this.getClass().getSimpleName())
            .start();
        
        try (Tracer.SpanInScope ws = tracer.withSpanInScope(span)) {
            // 添加追踪信息到上下文
            context.setAttribute("trace.id", span.context().traceId());
            context.setAttribute("span.id", span.context().spanId());
            
            // 执行实际的处理逻辑
            boolean result = processWithTracing(context);
            
            // 添加结果标签
            span.tag("result", String.valueOf(result));
            
            return result;
        } catch (Exception e) {
            span.tag("error", e.getMessage());
            throw e;
        } finally {
            span.end();
        }
    }
    
    protected boolean processWithTracing(Context<T, R> context) {
        // 子类实现具体的业务逻辑
        return true;
    }
}

扩展机制

1. 插件系统

java 复制代码
/**
 * 插件接口
 */
public interface ChainPlugin {
    
    /**
     * 插件名称
     */
    String getName();
    
    /**
     * 插件版本
     */
    String getVersion();
    
    /**
     * 初始化插件
     */
    void initialize(ChainPluginContext context);
    
    /**
     * 销毁插件
     */
    void destroy();
    
    /**
     * 插件是否启用
     */
    boolean isEnabled();
}

/**
 * 插件管理器
 */
public class ChainPluginManager {
    
    private final Map<String, ChainPlugin> plugins = new ConcurrentHashMap<>();
    private final ChainPluginContext pluginContext;
    
    public ChainPluginManager(ChainPluginContext pluginContext) {
        this.pluginContext = pluginContext;
    }
    
    /**
     * 注册插件
     */
    public void registerPlugin(ChainPlugin plugin) {
        if (plugins.containsKey(plugin.getName())) {
            throw new IllegalArgumentException("Plugin already registered: " + plugin.getName());
        }
        
        plugins.put(plugin.getName(), plugin);
        
        if (plugin.isEnabled()) {
            plugin.initialize(pluginContext);
        }
    }
    
    /**
     * 卸载插件
     */
    public void unregisterPlugin(String pluginName) {
        ChainPlugin plugin = plugins.remove(pluginName);
        if (plugin != null) {
            plugin.destroy();
        }
    }
    
    /**
     * 获取插件
     */
    public ChainPlugin getPlugin(String pluginName) {
        return plugins.get(pluginName);
    }
    
    /**
     * 获取所有插件
     */
    public Collection<ChainPlugin> getAllPlugins() {
        return plugins.values();
    }
    
    /**
     * 启用插件
     */
    public void enablePlugin(String pluginName) {
        ChainPlugin plugin = plugins.get(pluginName);
        if (plugin != null && !plugin.isEnabled()) {
            plugin.initialize(pluginContext);
        }
    }
    
    /**
     * 禁用插件
     */
    public void disablePlugin(String pluginName) {
        ChainPlugin plugin = plugins.get(pluginName);
        if (plugin != null && plugin.isEnabled()) {
            plugin.destroy();
        }
    }
}

2. 自定义扩展点

java 复制代码
/**
 * 扩展点接口
 */
public interface ExtensionPoint {
    
    /**
     * 扩展点名称
     */
    String getName();
    
    /**
     * 执行扩展逻辑
     */
    void execute(ExtensionContext context);
}

/**
 * 扩展点管理器
 */
public class ExtensionPointManager {
    
    private final Map<String, List<ExtensionPoint>> extensionPoints = new ConcurrentHashMap<>();
    
    /**
     * 注册扩展点
     */
    public void registerExtension(String pointName, ExtensionPoint extension) {
        extensionPoints.computeIfAbsent(pointName, k -> new ArrayList<>()).add(extension);
    }
    
    /**
     * 执行扩展点
     */
    public void executeExtensions(String pointName, ExtensionContext context) {
        List<ExtensionPoint> extensions = extensionPoints.get(pointName);
        if (extensions != null) {
            for (ExtensionPoint extension : extensions) {
                try {
                    extension.execute(context);
                } catch (Exception e) {
                    logger.error("Extension execution failed: {}", extension.getName(), e);
                }
            }
        }
    }
}

总结

责任链框架的高级应用提供了强大的功能扩展:

  1. 过滤器链:支持Web请求过滤、数据处理管道等场景
  2. 中断处理:提供优雅中断、超时控制等机制
  3. 性能优化:内存优化、并发优化、缓存优化等策略
  4. 监控诊断:性能监控、健康检查、分布式追踪等功能
  5. 扩展机制:插件系统、自定义扩展点等扩展能力

通过这些高级特性,责任链框架能够满足复杂企业级应用的需求,提供高性能、高可用、易扩展的解决方案。

最佳实践总结

  1. 合理设计处理器粒度:避免过于细粒度或粗粒度的处理器
  2. 注意性能影响:监控链的执行时间,避免过长的处理链
  3. 完善错误处理:提供多层次的错误处理和恢复机制
  4. 使用缓存优化:对于重复计算,合理使用缓存提升性能
  5. 监控和诊断:建立完善的监控体系,便于问题定位
  6. 文档和测试:提供清晰的文档和完整的测试用例

通过遵循这些最佳实践,可以构建出高质量、高性能的责任链框架应用。

相关推荐
掘金安东尼7 小时前
什么是 OKLCH 颜色?
前端·javascript·github
麦兜*7 小时前
MongoDB 高可用部署:Replica Set 搭建与故障转移测试
java·数据库·spring boot·后端·mongodb·spring cloud·系统架构
汤姆yu7 小时前
2025版基于springboot的电影购票管理系统
java·spring boot·后端·电影购票
悟乙己7 小时前
如何区分 Context Engineering 与 Prompt Engineering
android·java·prompt
头孢头孢7 小时前
基于 EasyExcel + 线程池 解决 POI 导出时的内存溢出与超时问题
java
写不出来就跑路7 小时前
电商金融贷款服务市场趋势与竞争分析
java·前端·人工智能
吗喽对你问好7 小时前
Java场景题面试合集
java·开发语言·面试
荣淘淘7 小时前
互联网大厂求职面试记:谢飞机的搞笑答辩
java·jvm·spring·面试·springboot·线程池·多线程
绝无仅有8 小时前
Go语言面试之 select 机制与使用场景分析
后端·面试·github