RocketMQ 常规消息

maven 工程添加库

<dependency>
    <groupId>org.apache.rocketmq</groupId>
    <artifactId>rocketmq-client</artifactId>
    <version>4.4.0</version>
</dependency>

gradle 工程添加库

compile 'org.apache.rocketmq:rocketmq-client:4.4.0'

注意:

客户端版本要和服务端版本的一致,或者会发生一些奇怪的问题:

我遇到过版本不一致会发生,消息无法确认消息消费,也就是说 客户端已经消费了,也提交成功了,但是服务端没有同步到!

注意: 要到控制台创建 Topic 队列名称

  • 同步发送消息(Send Messages Synchronously)
public class SyncProducer {
    public static void main(String[] args) throws Exception {
        //Instantiate with a producer group name.
        DefaultMQProducer producer = new
            DefaultMQProducer("please_rename_unique_group_name");
        // 设置 name server 服务地址, 这里是是设置本机
        producer.setNamesrvAddr("127.0.0.1:9876");
        // 启动实例
        producer.start();
        for (int i = 0; i < 100; i++) {
            //Create a message instance, specifying topic, tag and message body.
            Message msg = new Message("TopicTest" /* Topic */,
                "TagA" /* Tag */,
                ("Hello RocketMQ " +
                    i).getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
            );
            //Call send message to deliver message to one of brokers.
            SendResult sendResult = producer.send(msg);
            System.out.printf("%s%n", sendResult);
        }
        //Shut down once the producer instance is not longer in use.
        producer.shutdown();
    }
}
  • 异常发送消息(Send Messages Asynchronously)
public class AsyncProducer {
    public static void main(String[] args) throws Exception {
        //Instantiate with a producer group name.
        DefaultMQProducer producer = new DefaultMQProducer("please_rename_unique_group_name");
        // 设置 name server 服务地址, 这里是是设置本机
        producer.setNamesrvAddr("localhost:9876");
        //Launch the instance.
        producer.start();
        producer.setRetryTimesWhenSendAsyncFailed(0);

        int messageCount = 100;
        final CountDownLatch countDownLatch = new CountDownLatch(messageCount);
        for (int i = 0; i < messageCount; i++) {
            try {
                final int index = i;
                Message msg = new Message("Jodie_topic_1023",
                    "TagA",
                    "OrderID188",
                    "Hello world".getBytes(RemotingHelper.DEFAULT_CHARSET));
                producer.send(msg, new SendCallback() {
                    @Override
                    public void onSuccess(SendResult sendResult) {
                        countDownLatch.countDown();
                        System.out.printf("%-10d OK %s %n", index, sendResult.getMsgId());
                    }

                    @Override
                    public void onException(Throwable e) {
                        countDownLatch.countDown();
                        System.out.printf("%-10d Exception %s %n", index, e);
                        e.printStackTrace();
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        countDownLatch.await(5, TimeUnit.SECONDS);
        producer.shutdown();
    }
}
  • Send Messages in One-way Mode
public class OnewayProducer {
    public static void main(String[] args) throws Exception{
        //Instantiate with a producer group name.
        DefaultMQProducer producer = new DefaultMQProducer("please_rename_unique_group_name");
        // Specify name server addresses.
        producer.setNamesrvAddr("localhost:9876");
        //Launch the instance.
        producer.start();
        for (int i = 0; i < 100; i++) {
            //Create a message instance, specifying topic, tag and message body.
            Message msg = new Message("TopicTest" /* Topic */,
                "TagA" /* Tag */,
                ("Hello RocketMQ " +
                    i).getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
            );
            //Call send message to deliver message to one of brokers.
            producer.sendOneway(msg);
        }
        //Wait for sending to complete
        Thread.sleep(5000);        
        producer.shutdown();
    }
}

ClientConfig 配置初始化

private static ClientConfig initClientConfig() {

   ClientConfig mClientConfig = new ClientConfig();

  // 客户端本机 IP 地址,某些机器会发生无法识别客户端IP地址情况,需要应用在代码中强制指定
  // Name Server 地址列表,多个 NameServer 地址用分号 隔开
  mClientConfig.setNamesrvAddr("127.0.0.1:9876");
  // 客户端实例名称,客户端创建的多个 Producer、 Consumer 实际是共用一个内部实例(这个实例包含
  // 网络连接、线程资源等),默认值:DEFAULT
  mClientConfig.setInstanceName("DEFAULT");
  // 通信层异步回调线程数,默认值4
  mClientConfig.setClientCallbackExecutorThreads(10);
  // 轮询 Name Server 间隔时间,单位毫秒,默认:30000
  // mClientConfig.setPollNameServerInterval(30000);
  // 向 Broker 发送心跳间隔时间,单位毫秒,默认:30000
  mClientConfig.setHeartbeatBrokerInterval(30000);
  // 持久化 Consumer 消费进度间隔时间,单位毫秒,默认:5000
  mClientConfig.setPersistConsumerOffsetInterval(5000);

  return ClientConfig;
}

Producer 初始化

private static void initProducer() {
  try {
    DefaultMQProducer mProducer = new DefaultMQProducer();

    ClientConfig config = initClientConfig();
    mProducer.resetClientConfig(config);
    // 在发送消息时,自动创建服务器不存在的topic,默认创建的队列数 默认值 4
    mProducer.setDefaultTopicQueueNums(4);
    // 发送消息超时时间,单位毫秒 : 默认值 10000
    mProducer.setSendMsgTimeout(10000);
    // 消息Body超过多大开始压缩(Consumer收到消息会自动解压缩),单位字节 默认值 4096
    mProducer.setCompressMsgBodyOverHowmuch(4096);
    // 如果发送消息返回sendResult,但是sendStatus!=SEND_OK,是否重试发送 默认值 FALSE
    mProducer.setRetryAnotherBrokerWhenNotStoreOK(false);

    mProducer.setProducerGroup(DEFAULT_GROUP);
//			mProducer.setRetryTimesWhenSendAsyncFailed(3);
    mProducer.start();
  } catch (Exception e) {
    LOG.error("init producer error:", e);
  }
}

发送消息

public boolean sendMessage(String queue, String body, String tags) {
  try {
    if(StringUtils.isEmpty(tags))
    {
      tags = StringUtils.getEmpty();
    }
    Message msg = new Message(queue, tags, body.getBytes(RemotingHelper.DEFAULT_CHARSET));

    // Call send message to deliver message to one of brokers.
    SendResult sendResult = mProducer.send(msg);
    if (sendResult.getSendStatus() == SendStatus.SEND_OK) {
      return true;
    }
    LOG.warn("send queue error : " + FastJsonHelper.jsonEncode(sendResult));
  } catch (Exception e) {
    LOG.error("send queue error:", e);
  }
  return false;
}