系统对外提供的服务应该满足幂等特性,同一次请求多次处理得到的结果应该相同。
介绍一种简单的幂等策略:
1、请求到来时根据幂等关键字构造幂等记录,幂等关键字在数据表中应该满足唯一约束
2、尝试插入幂等记录
3、插入失败时,根据幂等关键字捞取记录,若已存在则将已存在记录的状态返回,若不存在则抛异常出去等待下次请求。
示例代码:
/**
* try insert idempotent strategy*
* @param request service request
* @return service result
*/
private Result tryInsertIdempotent(Request request) {
OrderDO orderDO = Convert.composeOrderDO(request.getRequestId());
try {
// 1.try insert to order table,use requestId as idempotent key
orderDAO.insert(orderDO);
} catch (DAOException e) {
// 2.query order table,to identify if order for current request has existed
BnsUniqueDO bnsUniqueDO = bnsUniqueDAO.load(idempotentNo);
if (bnsUniqueDO != null) {
// 3. use existed order to construct service result
OrderDO orderDO = OrderDAO.load(idempotentNo);
} else {
// 4. if there is no order for current request, throw DAOException
throw new ServiceException(ErrCodeEnum.DAL_OPERATION_EXCEPTION,
"biz unique check insert occurs db exception", e);
}
}
}