目录基础概念使用场景定义通用管道上下文定义管道上下文处理器定义业务上下文类型和所需处理器业务上下文处理器 - 校验处理器 - 生成模型实例处理器 - 持久化处理器 - 通知构建管道路由表定义管道执行器异步执行测试
基础概念
管道模式(Pipeline Pattern) 是责任链模式(Chain of Responsibility Pattern)的常用变体之一。在管道模式中,管道扮演着流水线的角色,将数据传递到一个加工处理序列中,数据在每个步骤中被加工处理后,传递到下一个步骤进行加工处理,直到全部步骤处理完毕。
PS:纯的责任链模式在链上只会有一个处理器用于处理数据,而管道模式上多个处理器都会处理数据。
使用场景
任务代码较为复杂,满足以下业务场景下可以考虑使用管道模式。
添加新的子步骤
删除旧的子步骤
交换子步骤顺序
替换子步骤实现
定义通用管道上下文
@Getter
@Setter
public abstract class PipelineContext {
private LocalDateTime startTime;
private LocalDateTime endTime;
private String errorMsg;
public String getSimpleName() {
return this.getClass().getSimpleName();
}
}
定义管道上下文处理器
public interface ContextHandler {
/**
* Handle context
*
* @param context context
* @return result
*/
boolean handle(T context);
}
定义业务上下文类型和所需处理器
业务上下文
@Data
@Builder
public class BatchCouponContext extends PipelineContext {
private Double lastIndex;
private Integer quantity;
private CouponBuildContext couponContext;
@Builder.Default
private List couponCodes = new ArrayList();
}
处理器 - 校验
@Component
@Slf4j
public class BatchCouponValidator implements ContextHandler {
@Override
public boolean handle(BatchCouponContext context) {
log.info("[{}] Start validation", context.getSimpleName());
boolean condition = false;
if (condition) {
context.setErrorMsg("Validation failure");
return false;
}
return true;
}
}
处理器 - 生成模型实例
@Component
@Slf4j
public class BatchCouponCreator implements ContextHandler {
@Override
public boolean handle(BatchCouponContext context) {
log.info("[{}] Start to create, current dictionary {}", context.getSimpleName(), context.getCouponContext().getDictionary());
for (int i = 0; i < context.getQuantity(); i++) {
boolean result = doSomething();
if (!result) {
return false;
}
}
return true;
}
}
处理器 - 持久化
@Component
@Slf4j
public class BatchCouponSaver implements ContextHandler {
@Override
public boolean handle(BatchCouponContext context) {
log.info("[{}] Start saving, data: {}", context.getSimpleName(), context.getCouponCodes());
return true;
}
}
处理器 - 通知
@Slf4j
@Component
public class BatchCouponNotifier implements ContextHandler {
@Override
public boolean handle(BatchCouponContext context) {
log.info("[{}] Start notice, data: {}", context.getSimpleName(), context.getCouponCodes());
return true;
}
}
构建管道路由表
@Configuration
public class PipelineRouteConfig {
HashMap |