在日常的业务处理中,责任链很常用,在此做记录
/**
* 校验调用链封装
*
* @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);
}
}