seata 手动回滚全局事务

1、seata 使用全局事务的时候,有时需要手动回滚事务,不需要抛异常则使用下面处理

import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.core.model.GlobalStatus;
import io.seata.core.model.TransactionManager;
import io.seata.spring.annotation.GlobalTransactional;
import io.seata.tm.TransactionManagerHolder;
import io.seata.tm.api.GlobalTransaction;
import io.seata.tm.api.GlobalTransactionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class TestServiceImpl implements ITestService {

    @Autowired
    private ProductCollectionService productCollectionService;

    @Autowired
    private BaseUserServiceClient baseUserServiceClient;

    @GlobalTransactional
    @Override
    public void test() {

        String xid = RootContext.getXID();
        TransactionManager manager = TransactionManagerHolder.get();
        try {
            log.info("test 获取事务id {}", xid);

            ProductCollection collection = new ProductCollection();
            collection.setProductId(1L);
            collection.setUserId(1L);
            collection.setCreateTime(new Date());
            productCollectionService.save(collection);

            ResultBody resultBody = baseUserServiceClient.increaseUserScore(1L, 2, "2");

            log.info("test 开始回滚数据");
            GlobalStatus status = manager.rollback(xid);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                manager.rollback(xid);
            } catch (TransactionException transactionException) {
                transactionException.printStackTrace();
            }
        }
    }

    @Override
    public void test1() {

        GlobalTransaction globalTransaction = GlobalTransactionContext.getCurrentOrCreate();

        try {
            globalTransaction.begin(300000, "my_test_tx_group");

            log.info("test1 获取事务 {}", globalTransaction.getXid());

            ProductCollection collection = new ProductCollection();
            collection.setProductId(1L);
            collection.setUserId(1L);
            collection.setCreateTime(new Date());
            productCollectionService.save(collection);

            ResultBody resultBody = baseUserServiceClient.increaseUserScore(1L, 2, "2");

            log.info("test1 开始回滚数据");
            globalTransaction.rollback();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                log.info("test1 开始回滚数据");
                globalTransaction.rollback();
            } catch (TransactionException transactionException) {
                transactionException.printStackTrace();
            }
        }
    }

}

你可能感兴趣的:(seata)