责任链模式应用场景
网关权限控制责任链模式
在网关作为微服务程序的入口,拦截客户端所有的请求实现权限控制 ,比如先判断Api接口限流、黑名单、用户会话、参数过滤。
Api接口限流→黑名单拦截→用户会话→参数过滤
责任链整合工厂模式
GatewayHandler抽象角色
public abstract class GatewayHandler {
protected GatewayHandler nextGatewayHandler;
/**
* 处理业务逻辑
*/
public abstract void doService();
/**
* 设置下一个GatewayHandler
*
* @return
*/
public void setNextGatewayHandler(GatewayHandler nextGatewayHandler) {
this.nextGatewayHandler = nextGatewayHandler;
}
}
具体Handler实现
package com.mayikt.chain.impl;
import com.mayikt.chain.GatewayHandler;
import lombok.extern.slf4j.Slf4j;
ngjun644
*/
@Slf4j
public class CurrentLimitHandler extends GatewayHandler {
@Override
public void doService() {
log.info("第一关:api 接口限流处理");
nextGatewayHandler.doService();
}
}
package com.mayikt.chain.impl;
import com.mayikt.chain.GatewayHandler;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class BlacklistHandler extends GatewayHandler {
@Override
public void doService() {
log.info("第二关:黑名单处理");
nextGatewayHandler.doService();
}
}
package com.mayikt.chain.impl;
import com.mayikt.chain.GatewayHandler;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class ConversationHandler extends GatewayHandler {
@Override
public void doService() {
log.info("第三关:验证会话信息处理流程");
}
}
FactoryHandler
package com.mayikt.chain.factory;
import com.mayikt.chain.GatewayHandler;
import com.mayikt.chain.impl.BlacklistHandler;
import com.mayikt.chain.impl.ConversationHandler;
import com.mayikt.chain.impl.CurrentLimitHandler;
public class FactoryHandler {
/**
* 设置下一个getGatewayHandler
* @return
*/
public static GatewayHandler getGatewayHandler() {
BlacklistHandler blacklistHandler = new BlacklistHandler();
blacklistHandler.setNextGatewayHandler(new ConversationHandler());
CurrentLimitHandler currentLimitHandler = new CurrentLimitHandler();
currentLimitHandler.setNextGatewayHandler(blacklistHandler);
return currentLimitHandler;
}
}
;