分布式事務08 TCC框架示例——hmily


分布式事務 08 TCC框架示例——hmily

市面常見TCC框架

  • Seata :阿里雲推出的組件,支持較多方案,主推AT(二階段+分布式鎖)
  • tcc-transaction:不和底層rpc耦合,使用dubbo,http,thrift,webservice都可
  • tx-lcn:支持常用的dubbo,springcloud框架,維護不頻繁,熱度有所下降
  • hmily:國內工程師開發,異步高性能TCC框架,適應國內環境
  • ByteTcc:國內開發,兼容JTA規范的TCC框架
  • EasyTransaction:柔性事務、TCC、SAGA、可靠消息等功能齊全,一站式解決

hmily框架

在Gitee上可以找到,demo位於hmily-demo模塊下

hmily框架demo——訂單扣減庫存

  • 代碼配置與流程
    先根據官方手冊,拉取代碼

hmily在代碼中的體現

  1. 在賬戶服務AccountServiceImpl中,通過使用@HmilyTCC注解,將方法聲明為TCC式分布式事務的方法
@Override
@HmilyTCC(confirmMethod = "confirm", cancelMethod = "cancel")
public boolean payment(final AccountDTO accountDTO) {
    LOGGER.info("============執行try付款接口===============");
    accountMapper.update(accountDTO);
    return Boolean.TRUE;
}

可以看到@HmilyTCC注解中有兩個屬性,confirmMethodcancelMethod。這兩個屬性需要填寫對應的方法名稱。

顧名思義,這兩個方法就是confirm階段與cancel階段處理事務的方法,連同將方法體本身作為try階段,共同組成了TCC分布式事務的三要素。

對應着可以看下confirm方法與cancel方法

/**
 * Confirm boolean.
 *
 * @param accountDTO the account dto
 * @return the boolean
 */
public boolean confirm(final AccountDTO accountDTO) {
    LOGGER.info("============執行confirm 付款接口===============");
    return accountMapper.confirm(accountDTO) > 0;
}


/**
 * Cancel boolean.
 *
 * @param accountDTO the account dto
 * @return the boolean
 */
public boolean cancel(final AccountDTO accountDTO) {
    LOGGER.info("============執行cancel 付款接口===============");
    return accountMapper.cancel(accountDTO) > 0;
}

此時也能看到TCC模型的些許弊端:一個接口需求,需要寫至少三個方法來保證TCC三要素,並且這三個方法需要開發者自己思考業務進行正向操作與反向操作的雙向開發。

  1. 關鍵注解

@HmilyTCC與@Hmily

RPC上面的Hmily注解的作用只是用於連接前后兩個微服務的,使它們處於同一個分布式事務之下。
比如Feign調用的庫存服務:

@FeignClient(value = "inventory-service")
public interface InventoryClient {
    
    /**
     * 庫存扣減.
     *
     * @param inventoryDTO 實體對象
     * @return true 成功
     */
    @RequestMapping("/inventory-service/inventory/decrease")
    @Hmily
    Boolean decrease(@RequestBody InventoryDTO inventoryDTO);
    
    /**
     * 模擬庫存扣減異常.
     *
     * @param inventoryDTO 實體對象
     * @return true 成功
     */
    @Hmily
    @RequestMapping("/inventory-service/inventory/mockWithTryException")
    Boolean mockWithTryException(@RequestBody InventoryDTO inventoryDTO);
}

各個微服務內部的@HmilyTCC才是真正用於處理分布式事務的(執行try,confirm,canel,維護事務日志等),如上文說的三段式方法。

  • 流程分析


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM