zhangfeng
2022-11-08 f241a39f07acc5d5ede28b4152d74cbb84e4885b
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
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.gkhy.safePlatform.equipment.common;
 
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;
 
import java.util.Date;
 
@Component
public class RocketMQTemplateHelper {
 
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
 
    private Logger logger = LoggerFactory.getLogger(this.getClass());
 
 
    /**
     * 事务提交后发送MQ
     * @param message
     * @param <T>
     */
    public <T> void syncSend(String destination, T message) {
        // 是否开启事务判断
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCommit() {
                    SendResult sendResult = rocketMQTemplate.syncSend(destination, message);
                    if(sendResult.getSendStatus() != SendStatus.SEND_OK){
                        logger.info("【安全物资和设备管理】事务提交后才发送MQ的消息发送失败!"+ new Date());
                    }else{
                        logger.info("【安全物资和设备管理】消息申请发送rocketMQ消息成功!"+ new Date());
                    }
                }
            });
        } else {
            SendResult sendResult = rocketMQTemplate.syncSend(destination, message);
            if(sendResult.getSendStatus() != SendStatus.SEND_OK){
                logger.info("【安全物资和设备管理】事务提交后才发送MQ的消息发送失败!"+ new Date());
            }else{
                logger.info("【安全物资和设备管理】消息申请发送rocketMQ消息成功!"+ new Date());
            }
        }
    }
}