互聯(lián)網(wǎng)業(yè)務冪等性實現(xiàn)之基于MySQL
背景
在互聯(lián)網(wǎng)業(yè)務領域中,我們經(jīng)常會遇到應用到請求冪等性問題,即多次重復請求,所得到的結果,和一次請求一致。
以某互聯(lián)網(wǎng)電商的取消訂單為例子,當訂單取消,需要返回給消費者下單所消費的虛擬產(chǎn)品,如優(yōu)惠券、紅包、京豆等。通過冪等形式,確保返還給消費者的權益不多、不少。
那冪等性具體開發(fā)是怎么實現(xiàn)的呢?本文帶來基于MySQL的UNIQUE KEY的實現(xiàn)方案。
實現(xiàn)
眾所周知,UNIQUE KEY是數(shù)據(jù)庫中的唯一索引,數(shù)據(jù)庫的記錄中不允許有重復的值,我們可以利用這點,在處理業(yè)務前,先進行唯一索引數(shù)據(jù)(如訂單id)的插入操作:
- 插入成功,說明是第一次插入,正常處理業(yè)務;
- 插入失敗,說明該業(yè)務邏輯已經(jīng)處理過了,不做處理,提前返回;
如此,即可實現(xiàn)冪等性。
1.數(shù)據(jù)庫設計
冪等性輔助表設計如下:
CREATE TABLE `idempotent_validate` (
`id` bigint NOT NULL,
`create_time` time DEFAULT NULL,
`order_id` bigint DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UK_orssam7fgn4uj0lo2sn4on6vg` (`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
其中的一個字段order_id,我們定義為唯一索引。
2.代碼編寫
我們主要實現(xiàn)了訂單取消方法cancelOrder:
package com.example.idempotentmysql.service.impl;
import com.example.idempotentmysql.bean.IdempotentValidate;
import com.example.idempotentmysql.bean.OrderInfo;
import com.example.idempotentmysql.bean.ProductInfo;
import com.example.idempotentmysql.bean.UserInfo;
import com.example.idempotentmysql.repository.IdempotentValidateRepository;
import com.example.idempotentmysql.repository.OrderInfoRepository;
import com.example.idempotentmysql.repository.ProductInfoRepository;
import com.example.idempotentmysql.repository.UserInfoRepository;
import com.example.idempotentmysql.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Optional;
/**
* 訂單服務
*
* @author hongcunlin
*/
@Service
public class OrderServiceImpl implements OrderService {
/**
* 日志
*/
private static final Logger LOGGER = LoggerFactory.getLogger(OrderServiceImpl.class);
/**
* 用戶repository
*/
@Resource
private UserInfoRepository userInfoRepository;
/**
* 商品repository
*/
@Resource
private ProductInfoRepository productInfoRepository;
/**
* 訂單repository
*/
@Resource
private OrderInfoRepository orderInfoRepository;
/**
* 冪等性校驗
*/
@Resource
private IdempotentValidateRepository idempotentValidateRepository;
/**
* 取消訂單(帶冪等性校驗)
*
* @param orderId 訂單id
*/
@Override
public void cancelOrder(Long orderId) {
// 1.冪等性校驗
try {
IdempotentValidate idempotentValidate = new IdempotentValidate();
idempotentValidate.setOrderId(orderId);
idempotentValidateRepository.save(idempotentValidate);
} catch (Exception e) {
LOGGER.info("訂單退款冪等");
return;
}
// 2.退款
Optional<OrderInfo> orderInfoOptional = orderInfoRepository.findById(orderId);
if (orderInfoOptional.isPresent()) {
OrderInfo orderInfo = orderInfoOptional.get();
Optional<UserInfo> userInfoOptional = userInfoRepository.findById(orderInfo.getUserId());
Optional<ProductInfo> productInfoOptional = productInfoRepository.findById(orderInfo.getProductId());
if (userInfoOptional.isPresent() && productInfoOptional.isPresent()) {
UserInfo userInfo = userInfoOptional.get();
ProductInfo productInfo = productInfoOptional.get();
userInfo.setMoney(userInfo.getMoney().add(productInfo.getPrice()));
userInfoRepository.save(userInfo);
}
}
LOGGER.info("訂單成功退款");
}
}
從代碼中可以看到,我們在除了訂單退款前,冪等性表先拿訂單id進行插入操作,若插入成功,說明是第一次取消訂單,執(zhí)行下面的退款邏輯;
若插入失敗,說明之前已經(jīng)進行過退款邏輯了,我們提前返回,不做下面的退款操作。
如此,便實現(xiàn)了訂單退款的冪等性。
3.測試
我們對訂單進行3次取消操作:
package com.example.idempotentmysql.service;
import com.example.idempotentmysql.bean.OrderInfo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
@SpringBootTest
public class OrderServiceTest {
@Resource
private OrderService orderService;
@Test
public void cancelOrderTest() {
orderService.cancelOrder(6L);
orderService.cancelOrder(6L);
orderService.cancelOrder(6L);
}
}
可以看到,只有第一次是退款成功的,后面2次觸發(fā)冪等性,退款失敗,符合我們的預期。
其他
冪等性的實現(xiàn)方式還有很多種,基于MySQL的UNIQUE KEY的實現(xiàn)方案,實現(xiàn)起來相當簡單,僅適合業(yè)務簡單,并發(fā)量不高的場景。原因是MySQL的qps有限,且MySQL作為系統(tǒng)的最底層的應用,過于后置,如果最終冪等返回,比較浪費前置的業(yè)務處理所消耗的資源。
本文代碼已經(jīng)上傳到github上了,有需要的同學可以下載參考:https://github.com/larger5/idempotent-mysql