RocketMQ的四种常用消息队列及代码演示

  @Service

  public class MyTransactionListener implements RocketMQLocalTransactionListener {

  @Override

  public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {

  // 执行本地事务

  // 如果本地事务执行成功,则返回RocketMQLocalTransactionState.COMMIT

  // 如果本地事务执行失败,则返回RocketMQLocalTransactionState.ROLLBACK

  return RocketMQLocalTransactionState.UNKNOWN;

  }

  @Override

  public RocketMQLocalTransactionState checkLocalTransaction(Message message) {

  // 检查本地事务状态

  // 如果本地事务执行成功,则返回RocketMQLocalTransactionState.COMMIT

  // 如果本地事务执行失败,则返回RocketMQLocalTransactionState.ROLLBACK

  // 如果本地事务状态未知,则返回RocketMQLocalTransactionState.UNKNOWN

  return RocketMQLocalTransactionState.UNKNOWN;

  }

  }

  @Service

  public class MyProducer {

  @Autowired

  private RocketMQTemplate rocketMQTemplate;

  @Autowired

  private MyTransactionListener transactionListener;

  public void sendTransactionMessage(String message) {

  rocketMQTemplate.setTransactionListener(transactionListener);

  rocketMQTemplate.sendMessageInTransaction("myTransactionGroup", "myTopic",

  MessageBuilder.withpayload(message).build(), null);

  }

  }