在繁琐的业务流程处理中,通常采用面向过程的设计方法将流程拆分成N个步骤,每个步骤执行独立的逻辑。
public void process(params){
doFirst(params);
doSecond(params);
....
doLast(params);
}
但是这样剥离仍然是不彻底的,修改其中一个步骤仍然可能影响其他步骤(同一个类修改,不符合开闭原则)。在这种场景下,有一种经典的设计模式-责任链模式,可以将这些子步骤封装成独立的handler,然后通过pipeline将其串联起来。
常见的责任链模式会设计如下:
总体来看,纯手动编写有以下问题:
那有没有一套靠谱的框架能够解决上述问题呢?有的,它就是foldright/auto-pipeline,是责任链领域的"lombok"!
下面以读取系统配置为例,读取逻辑如下:
为了实现这个需求,读取配置接口定义如下:
public interface ConfigSource {
String get(String key);
}
如果使用auto-pipeline,该如何
以下大部分内容引至auto-pipeline官网: https://github.com/foldright/auto-pipeline
引入Maven依赖
<dependency>
<groupId>com.foldright.auto-pipeline</groupId>
<artifactId>auto-pipeline-processor</artifactId>
<version>0.2.0</version>
<scope>provided</scope>
</dependency>
在需要生成pipeline的接口上加上@AutoPipeline
只需为这个接口加上@AutoPipeline
public interface ConfigSource {
String get(String key);
}
实现pipeline的handler
public class MapConfigSourceHandler implements ConfigSourceHandler {
private final Map<String, String> map;
public MapConfigSourceHandler(Map<String, String> map) {
this.map = map;
}
public String get(String key, ConfigSourceHandlerContext context) {
String value = map.get(key);
if (StringUtils.isNotBlank(value)) {
return value;
}
return context.get(key);
}
}
public class SystemConfigSourceHandler implements ConfigSourceHandler {
public static final SystemConfigSourceHandler INSTANCE = new SystemConfigSourceHandler();
public String get(String key, ConfigSourceHandlerContext context) {
String value = System.getProperty(key);
if (StringUtils.isNotBlank(value)) {
return value;
}
return context.get(key);
}
}
使用pipeline
Map<String, String> mapConfig = new HashMap<String, String>();
mapConfig.put("hello", "world");
ConfigSourceHandler mapConfigSourceHandler = new MapConfigSourceHandler(mapConfig);
ConfigSource pipeline = new ConfigSourcePipeline()
.addLast(mapConfigSourceHandler)
.addLast(SystemConfigSourceHandler.INSTANCE);
pipeline.get("hello");
// get value "world"
// from mapConfig / mapConfigSourceHandler
pipeline.get("java.specification.version")
// get value "1.8"
// from system properties / SystemConfigSourceHandler
业务接口通过生成的Pipeline构造实现,Pipeline负责责任链的组装及调用链表的首个节点(head)。首个节点如果处理完成有返回值,则直接返回;否则传递给下一个节点。如果处理到最后一个节点(tail)返回仍然为空,则直接返回空。
以获取配置为例:
目录
一些实例,比如获取配置、rpc、merger
生成原理
通过SPI的方式注册编译时注解@AutoPipelineProcessor,在编译过程中通过javapoet框架生成业务pipeline源代码。
相关类介绍:
JDK术语介绍:
override fun process(annotations: Set<TypeElement>, roundEnv: RoundEnvironment): Boolean {
val elements = roundEnv.getElementsAnnotatedWith(AutoPipeline::class.java)
if (elements.isEmpty()) {
return false
}
for (element in elements) {
if (element.kind != ElementKind.INTERFACE) {
error(element, "${(element as TypeElement).qualifiedName} is not a interface! Only interface can annotated with @${AutoPipeline::class.simpleName}")
return false
}
if (!element.modifiers.contains(Modifier.PUBLIC)) {
error(element, "interface ${(element as TypeElement).qualifiedName} is not public! Only public interface can annotated with @${AutoPipeline::class.simpleName}")
return false
}
if (element is TypeElement) {
doProcess(element)
}
}
return false
}
生成相关源代码,一个源文件采用一个特定的代码生成器生成,各个类的生成器继承AbstractGenerator
下面以HandlerGenerator#gen 为例:
fun gen() {
// 生成类
val handlerTypeBuilder = TypeSpec.interfaceBuilder(desc.handlerRawClassName)
.addTypeVariables(desc.entityDeclaredTypeVariables)
.addModifiers(Modifier.PUBLIC)
// 构建handlerContext参数
val contextParam = ParameterSpec.builder(
desc.handlerContextTypeName, desc.handlerContextRawClassName.asFieldName()
).build()
// 为原来接口的每个方法额外添加handlerContext参数
desc.entityMethods.forEach {
val operationMethod = createMethodSpecBuilder(it.executableElement)
.addParameter(contextParam)
.build()
handlerTypeBuilder.addMethod(operationMethod)
}
// 生成源码
javaFileBuilder(desc.handlerRawClassName.packageName(), handlerTypeBuilder.build())
.build()
.writeTo(filer)
}
编译Debug探秘
可以通过Idea Maven自带的Debug工具 调试编译过程
下面举一个项目中真实的例子-消息分级限流。
消息发送的流量现状:
每个消息都会有对应的Appkey、消息分级
限流规则如下:
需要对消息所属的AppKey进行单独限流
仅对营销类消息进行限流,IM&实时类消息无需限流
如果一个消息已经被一个接口限流过,经过下一个接口时不应该被限流
面对这种的场景,该如何设计呢?
将整体限流和整体不限流抽象成合并策略,通过proxy的方式对外暴露
限流接口类
/**
* 消息限流器
*/
public interface MessageThrottler {
/**
* 节流单个消息
*
* @param messageThrottlerToken 消息限流令牌
* @return 是否被节流
*/
boolean throttle(MessageThrottlerToken messageThrottlerToken);
/**
* 节流多个消息。任意一个消息被节流将返回true,否则返回false
*
* @param messageThrottlerTokens 多个消息限流令牌
* @return 是否被节流
*/
boolean anyThrottle(List<MessageThrottlerToken> messageThrottlerTokens);
/**
* 节流多个消息。所有消息被节流才会返回true, 否则返回false
*
* @param messageThrottlerTokens 多个消息限流令牌
* @return 是否被节流
*/
boolean allThrottle(List<MessageThrottlerToken> messageThrottlerTokens);
}
ClassificationThrottlerHandler
/**
* 消息分类节流器
*
* <p>
* 目前仅针对营销消息进行节流
*/
public class ClassificationThrottlerHandler implements MessageThrottlerHandler {
public boolean throttle(MessageThrottlerToken messageThrottlerToken, MessageThrottlerHandlerContext context) {
if (!ClassificationConstant.MARKETING.equals(messageThrottlerToken.getClassification())) {
return false;
}
return context.throttle(messageThrottlerToken);
}
public boolean anyThrottle(List<MessageThrottlerToken> messageThrottlerTokens, MessageThrottlerHandlerContext context) {
if (CollectionUtils.isEmpty(messageThrottlerTokens)) {
return false;
}
// 获取营销消息
List<MessageThrottlerToken> marketingMessageThrottlerTokens = messageThrottlerTokens.stream().filter(messageThrottlerToken -> {
return ClassificationConstant.MARKETING.equals(messageThrottlerToken.getClassification());
}).collect(Collectors.toList());
// 如果营销消息为空,说明消息均不需要被限流,直接返回false
if (CollectionUtils.isEmpty(marketingMessageThrottlerTokens)) {
return false;
}
return context.anyThrottle(marketingMessageThrottlerTokens);
}
public boolean allThrottle(List<MessageThrottlerToken> messageThrottlerTokens, MessageThrottlerHandlerContext context) {
if (CollectionUtils.isEmpty(messageThrottlerTokens)) {
return false;
}
// 获取营销消息
List<MessageThrottlerToken> marketingMessageThrottlerTokens = messageThrottlerTokens.stream().filter(messageThrottlerToken -> {
return ClassificationConstant.MARKETING.equals(messageThrottlerToken.getClassification());
}).collect(Collectors.toList());
// 存在非营销消息,非营销消息不会被限流
if (marketingMessageThrottlerTokens.size() < messageThrottlerTokens.size()) {
return false;
}
return context.allThrottle(marketingMessageThrottlerTokens);
}
}
DuplicateThrottlerHandler
4j
public class DuplicateThrottlerHandler implements MessageThrottlerHandler {
public boolean throttle(MessageThrottlerToken messageThrottlerToken, MessageThrottlerHandlerContext context) {
if (messageThrottlerToken.isThrottled()) {
return false;
}
boolean throttleResult = context.throttle(messageThrottlerToken);
messageThrottlerToken.markThrottled();
return throttleResult;
}
public boolean anyThrottle(List<MessageThrottlerToken> messageThrottlerTokens, MessageThrottlerHandlerContext context) {
if (CollectionUtils.isEmpty(messageThrottlerTokens)) {
return false;
}
// 过滤掉已经被限流的消息
List<MessageThrottlerToken> needMessageThrottlerTokens = messageThrottlerTokens.stream()
.filter(messageThrottlerToken -> !messageThrottlerToken.isThrottled()).collect(Collectors.toList());
if (CollectionUtils.isEmpty(needMessageThrottlerTokens)) {
return false;
}
boolean throttleResult = context.anyThrottle(needMessageThrottlerTokens);
needMessageThrottlerTokens.forEach(messageThrottlerToken -> messageThrottlerToken.markThrottled());
return throttleResult;
}
public boolean allThrottle(List<MessageThrottlerToken> messageThrottlerTokens, MessageThrottlerHandlerContext context) {
if (CollectionUtils.isEmpty(messageThrottlerTokens)) {
return false;
}
// 过滤掉已经被限流的消息
List<MessageThrottlerToken> needMessageThrottlerTokens = messageThrottlerTokens.stream()
.filter(messageThrottlerToken -> !messageThrottlerToken.isThrottled()).collect(Collectors.toList());
if (CollectionUtils.isEmpty(needMessageThrottlerTokens)) {
return false;
}
boolean throttleResult = context.allThrottle(needMessageThrottlerTokens);
needMessageThrottlerTokens.forEach(messageThrottlerToken -> messageThrottlerToken.markThrottled());
return throttleResult;
}
}
AcquireThrottlerHandler
/**
* 请求令牌处理类
*/
public class AcquireThrottlerHandler implements MessageThrottlerHandler {
private static final Logger apiThrottlerLog = LoggerFactory.getLogger("api.throttler.log");
private ThrottlerProxy throttlerProxy;
private ThrottlerModeConfiguration throttlerModeConfiguration;
private boolean throttle(AcquireToken acquireToken) {
// 获取限流模式
ThrottlerMode throttlerMode = throttlerModeConfiguration.getThrottlerMode(acquireToken.getAppKey(), acquireToken.getThrottleTag());
// 执行限流
return !throttlerProxy.tryAcquireWithAppKey(throttlerMode, acquireToken.getAppKey(), acquireToken.getPermits());
}
public boolean throttle(MessageThrottlerToken messageThrottlerToken, MessageThrottlerHandlerContext context) {
boolean throttled = throttle(new AcquireToken(messageThrottlerToken.getThrottleTag(), messageThrottlerToken.getAppKey(), messageThrottlerToken.getPermits()));
// 限流日志埋点
if (SendSwitch.THROTTLER_ONLY_WATCH || throttled) {
log(messageThrottlerToken.getAppKey(), messageThrottlerToken.getPermits(), messageThrottlerToken.getThrottleTag(), throttled);
}
return throttled;
}
public boolean anyThrottle(List<MessageThrottlerToken> messageThrottlerTokens, MessageThrottlerHandlerContext context) {
return throttle(messageThrottlerTokens, acquireTokens -> acquireTokens.stream().anyMatch(this::throttle)
);
}
public boolean allThrottle(List<MessageThrottlerToken> messageThrottlerTokens, MessageThrottlerHandlerContext messageThrottlerHandlerContext) {
return throttle(messageThrottlerTokens, acquireTokens -> acquireTokens.stream().allMatch(this::throttle)
);
}
private static boolean throttle(List<MessageThrottlerToken> messageThrottlerTokens, Function<List<AcquireToken>, Boolean> function) {
if (CollectionUtils.isEmpty(messageThrottlerTokens)) {
return false;
}
List<AcquireToken> acquireTokens = messageThrottlerTokens.stream()
.collect(Collectors.groupingBy(messageThrottlerToken -> messageThrottlerToken.getAppKey()))
.entrySet()
.stream()
.map(messageEntry -> {
String appKey = messageEntry.getKey();
int permits = messageEntry.getValue().stream()
.map(messageThrottlerToken -> messageThrottlerToken.getPermits())
.reduce(Integer::sum).orElse(1);
String throttlerTag = messageEntry.getValue().get(0).getThrottleTag();
return new AcquireToken(throttlerTag, appKey, permits);
}).collect(Collectors.toList());
boolean throttled = function.apply(acquireTokens);
// 限流日志埋点
if (SendSwitch.THROTTLER_ONLY_WATCH || throttled) {
messageThrottlerTokens.forEach(messageThrottlerToken -> {
log(messageThrottlerToken.getAppKey(), messageThrottlerToken.getPermits(), messageThrottlerToken.getThrottleTag(), throttled);
});
}
return throttled;
}
private static void log(String appKey, int permits, String throttlerTag, boolean throtted) {
List<String> metrics = new ArrayList<>();
metrics.add(appKey);
metrics.add(String.valueOf(permits));
metrics.add(throttlerTag);
metrics.add(String.valueOf(throtted));
String logContent = StringUtils.join(metrics, "|");
apiThrottlerLog.info(logContent);
}
private static class AcquireToken {
private final String throttleTag;
private final String appKey;
private final int permits;
}
}
消息限流代理
/**
* 消息限流代理
*/
4j
public class MessageThrottlerProxy {
private AcquireThrottlerHandler acquireThrottlerHandler;
private MessageThrottler messageThrottler;
public void init() {
messageThrottler = new MessageThrottlerPipeline()
.addLast(new ClassificationThrottlerHandler())
.addLast(new DuplicateThrottlerHandler())
.addLast(acquireThrottlerHandler);
}
/**
* 限流单个消息
*
* @param messageThrottlerToken 单个消息令牌
* @return 是否限流成功
*/
public boolean throttle(MessageThrottlerToken messageThrottlerToken) {
if (!SendSwitch.ENABLE_API_THROTTLER) {
return false;
}
try {
boolean throttled = messageThrottler.throttle(messageThrottlerToken);
return SendSwitch.THROTTLER_ONLY_WATCH ? false : throttled;
} catch (Exception e) {
log.error("Failed to throttle messageSendDTO:" + messageThrottlerToken, e);
// throttle内部异常不应该影响正常请求,遇到此情况直接降级限流通过
return false;
}
}
/**
* 限流多个消息, 合并策略可通过 {@link SendSwitch#THROTTLER_MERGE_STRATEGY} 开关控制
*
* @param messageThrottlerTokens 多个消息令牌
* @return 是否限流成功
*/
public boolean throttle(List<MessageThrottlerToken> messageThrottlerTokens) {
if (!SendSwitch.ENABLE_API_THROTTLER) {
return false;
}
if (CollectionUtils.isEmpty(messageThrottlerTokens)) {
return false;
}
MergeStrategy mergeStrategy = MergeStrategy.getByName(SendSwitch.THROTTLER_MERGE_STRATEGY);
if (mergeStrategy == null) {
log.error("illegal throttler mergeStrategy:" + SendSwitch.THROTTLER_MERGE_STRATEGY);
return false;
}
try {
boolean throttled = mergeStrategy.throttle(messageThrottler, messageThrottlerTokens);
return SendSwitch.THROTTLER_ONLY_WATCH ? false : throttled;
} catch (Exception e) {
log.error("Failed to throttle messageSendDTO:" + messageThrottlerTokens, e);
// throttle内部异常不应该影响正常请求,遇到此情况直接降级限流通过
return false;
}
}
public enum MergeStrategy {
ALL {
public boolean throttle(MessageThrottler messageThrottler, List<MessageThrottlerToken> messageThrottlerTokens) {
return messageThrottler.allThrottle(messageThrottlerTokens);
}
},
ANY {
public boolean throttle(MessageThrottler messageThrottler, List<MessageThrottlerToken> messageThrottlerTokens) {
return messageThrottler.anyThrottle(messageThrottlerTokens);
}
};
public static MergeStrategy getByName(String name) {
MergeStrategy[] values = values();
for (MergeStrategy value : values) {
if (value.name().equalsIgnoreCase(name)) {
return value;
}
}
return null;
}
public abstract boolean throttle(MessageThrottler messageThrottler, List<MessageThrottlerToken> messageThrottlerTokens);
}
}
ps: 相关类并未全部列出,仅展示主要逻辑
推荐阅读
重磅来袭!2022上半年阿里云社区最热电子书榜单!
千万阅读量、百万下载量、上百本电子书,近200位阿里专家参与编写。多元化选择、全领域覆盖,汇聚阿里巴巴技术实践精华,读、学、练一键三连。开发者藏经阁,开发者的工作伴侣~
点击阅读原文查看详情。