hyperf icon indicating copy to clipboard operation
hyperf copied to clipboard

[QUESTION] 微服务 分布式事务 回滚没有生效 只能用http调用

Open sanzhangshitou opened this issue 3 months ago • 1 comments

Before you submit an issue, please be sure to search through existing issues as well as search through the documentation

  • [] I've searched all existing issues
  • [] I've read all relevant documentation I could find

Describe your question

调用外部服务

<?php

declare(strict_types=1);

namespace App\Service;

use App\JsonRpc\RpcOrderServiceInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Retry\Annotation\Retry;
use DtmClient\XA;

class OrderService
{
    const SERVICE_URI = 'http://localhost:9501/dtm';
    #[Inject]
    protected RpcOrderServiceInterface $rpcOrderService;

    #[Inject]
    private XA $xa;

    #[Retry]
    public function createOrder(): int
    {
        $res = 0;
        // 分布式事务调用 RPC
        $gid = $this->xa->generateGid();
        try {
            $this->xa->globalTransaction($gid, function () use (&$res) {
                $this->xa->callBranch(self::SERVICE_URI . '/RpcOrderServiceInterface/createTest', []);
                $this->xa->callBranch(self::SERVICE_URI . '/RpcOrderServiceInterface/createTestError', []);
            });
        } catch (\Throwable $th) {
            throw $th;
        }
        return $res;
    }
}

路由

<?php

declare(strict_types=1);

use Hyperf\HttpServer\Router\Router;
use App\JsonRpc\RpcOrderServiceInterface;

Router::addGroup('/dtm', function () {
    Router::addGroup('/RpcOrderServiceInterface', function () {
        Router::post('/createTest', function (RpcOrderServiceInterface $rpcOrderService) {
            return $rpcOrderService->createTest();
        });
        Router::post('/createTestError', function (RpcOrderServiceInterface $rpcOrderService) {
            return $rpcOrderService->createTestError();
        });
    });
});

上面的写法测试了没有生效

不支持写成这样的 不能直接用rpc服务调用 只能用http请求 有什么好的办法吗

            $this->xa->globalTransaction($gid, function () use (&$res) {
                // $this->xa->callBranch(self::SERVICE_URI . '/RpcOrderServiceInterface/createTest', []);
                // $this->xa->callBranch(self::SERVICE_URI . '/RpcOrderServiceInterface/createTestError', []);
                $this->xa->callBranch($this->rpcOrderService->createTest());
                $this->xa->callBranch($this->rpcOrderService->createTestError());
            });

sanzhangshitou avatar Oct 17 '25 11:10 sanzhangshitou

分布式事务 没办法直接内部 rpc 调用生效

sanzhangshitou avatar Oct 17 '25 12:10 sanzhangshitou