郑永安
2023-09-19 69185134fcfaf913ea45f1255677225a2cc311a4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.gk.hotwork.specialWork.common;
 
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
 
@Component
public class RocketMQSpecialWorkTemplateHelper {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
 
    /**
     * 事务提交后发送MQ
     * @param message
     * @param <T>
     */
    public <T> void syncSend(String destination, T message) {
        // 是否开启事务判断
        if (org.springframework.transaction.support.TransactionSynchronizationManager.isSynchronizationActive()) {
            org.springframework.transaction.support.TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCommit() {
                    SendResult sendResult = rocketMQTemplate.syncSend(destination, message);
                    if(sendResult.getSendStatus() != SendStatus.SEND_OK){
                        throw new RuntimeException("【特殊作业】发送MQ的消息失败"+message);
                    }
                }
            });
        } else {
            SendResult sendResult = rocketMQTemplate.syncSend(destination, message);
            if(sendResult.getSendStatus() != SendStatus.SEND_OK){
                throw new RuntimeException("【特殊作业】发送MQ的消息失败"+message);
            }
        }
    }
}