基於springBoot的責任鏈模式
在日常的業務處理中,責任鏈很常用,在此做記錄
/**
* 校驗呼叫鏈封裝
*
* @author nanfengxiangbei
* @date 2022/3/7
*/
@Component
public class ToPayCheckerMaster extends ToPayAbstractChecker {
@Autowired
public ToPayCheckerMaster(ToPaySignChecker toPaySignChecker,
ToPayAccessChecker toPayAccessChecker) {
// 設定校驗呼叫鏈(注意先後順序)
// --簽名校驗
setNext(toPaySignChecker);
// -- 許可權校驗
toPaySignChecker.setNext(toPayAccessChecker);
}
/**
* 啟動校驗
*
* @param toPayBo 申請上下文
*/
@Override
public void check(ToPayBo toPayBo) {
checkNext(toPayBo);
}
}
/**
* 校驗呼叫鏈抽象類
*
* @author nanfengxiangbei
* @date 2022/3/7
*/
public abstract class ToPayAbstractChecker {
/**
* 下一個校驗物件
*/
protected ToPayAbstractChecker next;
/**
* 執行校驗
*
* @param toPayBo 上下文
*/
public abstract void check(ToPayBo toPayBo);
protected void checkNext(ToPayBo toPayBo) {
if (toPayBo.getRespVo().getCode().equals(PayInterfaceStatusEnum.SUCCESS.getCode()) && next != null) {
next.check(toPayBo);
}
}
public void setNext(ToPayAbstractChecker next) {
this.next = next;
}
}
/**
* 簽名校驗
*
* @author nanfengxiangbei
* @date 2022/3/7
*/
@Component
public class ToPaySignChecker extends ToPayAbstractChecker {
private final Logger logger = LoggerFactory.getLogger(ToPaySignChecker.class);
@NacosValue(value = "${toPay.signChecker.join}", autoRefreshed = true)
private boolean join;
/**
* 執行校驗
*
* @param toPayBo 上下文
*/
@Override
public void check(ToPayBo toPayBo) {
// 通過nacos註解實現鏈的加入,或者移除
if (join) {
doCheck(toPayBo);
} else {
logger.info("Sign checker not join");
}
//
checkNext(toPayBo);
}
private void doCheck(ToPayBo toPayBo) {
long startTime = System.currentTimeMillis();
logger.info("簽名校驗,結果:{},耗時:{}", toPayBo.getRespVo().getCode(), System.currentTimeMillis() - startTime);
}
}
@Component
public class ToPayAccessChecker extends ToPayAbstractChecker {
private final Logger logger = LoggerFactory.getLogger(ToPayAccessChecker.class);
private static final String EQUITY_PRODUCT_APP_ID = "1000";
@NacosValue(value = "${toPay.accessPermChecker.join}", autoRefreshed = true)
private boolean join;
/**
* 執行校驗
*
* @param toPayBo 上下文
*/
@Override
public void check(ToPayBo toPayBo) {
if (join) {
doCheck(toPayBo);
} else {
logger.info("Access Permission checker not join");
}
//
checkNext(toPayBo);
}
private void doCheck(ToPayBo toPayBo) {
long startTime = System.currentTimeMillis();
//
logger.info("結果:{},耗時:{}", toPayBo.getRespVo().getCode(), System.currentTimeMillis() - startTime);
}
}