
package com.tmerclub.cloud.group.listener;

import com.tmerclub.cloud.group.bo.mongo.MongoGroupTeamBO;
import com.tmerclub.cloud.group.service.GroupTeamService;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;


/**
 * 拼团参团或开团，团队信息更新或保存到mongodb
 * 需要确保团队信息更新成功，否则其他mq消息可能会有幂等性问题
 * @author tmerclub
 * @date 2021/1/7
 */
@Component
@RocketMQTransactionListener(rocketMQTemplateBeanName = "sendGroupOrderOpenAndJoinGroupTemplate", maximumPoolSize = 20)
public class GroupOrderOpenAndJoinTransactionListener implements RocketMQLocalTransactionListener {

    @Autowired
    private GroupTeamService groupTeamService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object groupTeam) {
        groupTeamService.saveToMongodb((MongoGroupTeamBO) groupTeam);
        return RocketMQLocalTransactionState.COMMIT;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        // 直接回滚，防止异步出现aba的问题
        // 第二个原因是因为上面那个事务消息会重复发送多次，因为GROUP_ORDER_UN_SUCCESS_TOPIC 这个会回调多次
        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
