Spring Boot整合RocketMQ事务消息 注解版

生产者(Producer)端 事务消息发送

	//生产者端发生事务消息
 	Message<String> message1= MessageBuilder
 	//消息内容
 	.withPayload("你好")
 	//设置key
 	//setHeader同时也可以设置tags和sql过滤标识
 	.setHeader("KEYS","11111111").build();
 	
   	TransactionSendResult sendResult = rocketMQTemplate
   	/* * @param txProducerGroup		生产者端消息监听器名称
     * @param destination			主题:tags(:隔开)	
     * @param message				消息内容
     * @param arg					可以传入生产者端监听器 事务处理的方法中
     */
   	.sendMessageInTransaction("myGroup1","topic1:tags" ,message1,"hello");

生产者(Producer)端 消息监听器

@Slf4j
@RocketMQTransactionListener(txProducerGroup = "myGroup1")
public class MQTheTransaction implements RocketMQLocalTransactionListener {
	//	Object o 就是之前传入的对象 arg ( "hello" )
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        log.info("开始本地事务");
       // 执行本地事务
        RocketMQLocalTransactionState result = RocketMQLocalTransactionState.COMMIT;
        try {
            String jsonString = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8);
            String userName = (String) o;
        } catch (Exception e) {
            log.error(">>>> exception message={} <<<<",e.getMessage());
            result = RocketMQLocalTransactionState.UNKNOWN;
        }
        return result;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        log.info("事务回查");
        // 检查本地事务
        RocketMQLocalTransactionState result = RocketMQLocalTransactionState.COMMIT;
        try {
            String jsonString = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8);

        } catch (Exception e) {
            // 异常就回滚
            log.error("回滚");
            result = RocketMQLocalTransactionState.ROLLBACK;
        }
       return result;
    }
}

消费者 (consumer)端 监听器

/**
 * 必须继承 RocketMQListener<MessageExt>
 */
@Slf4j
@Component
// topic                主题
//consumerGroup         消费者组
//messageModel          消费模式(集群,广播)
//selectorType          选择过滤策略,tag 和sql
//selectorExpression    过滤规则
@RocketMQMessageListener(topic = "topic1", consumerGroup = "${rocketmq.cousumer.group}", messageModel = MessageModel.BROADCASTING,selectorType= SelectorType.TAG,selectorExpression="*")
public class 事务消费者 implements RocketMQListener<MessageExt>, RocketMQPushConsumerLifecycleListener {
    private int count = 0;

    @Override
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {

        System.out.println("开启");

        defaultMQPushConsumer.registerMessageListener(new MessageListenerConcurrently() {

            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {

                for (MessageExt messageExt : msgs) {


                    System.out.println("重试次数:" + messageExt.getReconsumeTimes());
                    System.out.println("key:" + messageExt.getKeys());
                    // 注意可以在此处判断重试次数,实现入库插入,记录相关消息,进行下面的业务逻辑处理

                    if (count == 0) {

                        count++;

                        return ConsumeConcurrentlyStatus.RECONSUME_LATER;

                    }

                    System.out.println("接受到的消息:" + new String(messageExt.getBody()));

                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;

                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;

            }

        });
    }

    @Override
    public void onMessage(MessageExt messageExt) {

    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值