Message msg = new Message("YOUR TOPIC",
"Hello world".getBytes(RemotingHelper.DEFAULT_CHARSET));
/*发送延时消息,需要设置延时时间,单位毫秒(ms),消息将在指定延时时间后投递,例如消息将在3秒后投递。*/
long delayTime = System.currentTimeMillis() + 3000;
msg.putUserProperty("__STARTDELIVERTIME", String.valueOf(delayTime));
*若需要发送定时消息,则需要设置定时时间,消息将在指定时间进行投递,例如消息将在2021-08-10 18:45:00投递。
*定时时间格式为:yyyy-MM-dd HH:mm:ss,若设置的时间戳在当前时间之前,则消息将被立即投递给Consumer。
* long timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2021-08-10 18:45:00").getTime();
* msg.putUserProperty("__STARTDELIVERTIME", String.valueOf(timeStamp));
SendResult sendResult = producer.send(msg);
System.out.printf("%s%n", sendResult);
// 如果需要取消之前延时的消息,再添加以下代码
Message cancelMsg = new Message("YOUR TOPIC",
"cancel".getBytes(StandardCharsets.UTF_8));
// 设置取消消息的时间戳,该时间戳必须与要取消的定时消息的定时时间戳一致
cancelMsg.putUserProperty("__STARTDELIVERTIME", String.valueOf(delayTime));
// 设置要取消消息的ID,为发送消息的唯一ID(UNIQUE_KEY),可以从发送消息的结果中获取
cancelMsg.putUserProperty("__CANCEL_SCHEDULED_MSG", sendResult.getMsgId());
// 发送取消消息,必须在定时消息被投递之前发送才可以取消,发给指定的 broker node queue 节点,没有 broker 信息的情况下,需要发给所有 broker 节点
SendResult cancelSendResult = producer.send(cancelMsg, sendResult.getMessageQueue());
//消息发送失败,需要进行重试处理,可重新发送这条消息或持久化这条数据进行补偿处理。
System.out.println(new Date() + " Send mq message failed.");