1.在linux上安装rocketmq后,启动正常:

nohup sh bin/mqnamesrv &
nohup sh bin/mqbroker -n localhost:9876 &

2.然后发送/接收消息测试都是ok的:
发送消息:
export NAMESRV_ADDR=localhost:9876
sh bin/tools.sh org.apache.rocketmq.example.quickstart.Producer
接收消息:
sh bin/tools.sh org.apache.rocketmq.example.quickstart.Consumer

 

3.用java代码发送消息报错:

代码:

public class SyncProducer {
    public static void main(String[] args) throws Exception {
       // 创建一个producer,参数为Producer Group名称
        DefaultMQProducer producer = new DefaultMQProducer("test");
        // 指定nameServer地址
        producer.setNamesrvAddr("192.168.124.10:9876");
        // 设置当发送失败时重试发送的次数,默认为2次
        producer.setRetryTimesWhenSendFailed(3);
        // 设置发送超时时限为5s,默认3s
        producer.setSendMsgTimeout(5000);
        // 开启生产者
        producer.start();

        for (int i = 0; i < 10; i++) {
            byte[] body = ("hello," + i).getBytes();
            Message msg = new Message("TopicTest", "TagA", body);
            // 发送消息
            SendResult sendResult = producer.send(msg);
            System.out.println(sendResult);
        }
        producer.shutdown();
    }
}

出现过的异常:

Exception in thread "main" org.apache.rocketmq.remoting.exception.RemotingTooMuchRequestException: sendDefaultImpl call timeout

Caused by: org.apache.rocketmq.remoting.exception.RemotingTimeoutException: invokeSync call timeout

Exception in thread "main" org.apache.rocketmq.client.exception.MQClientException: No route info of this topic

4.解决办法:

1.可能生产者启动未完成就发送消息了,建议在producer.start();后等待几秒

// 开启生产者
producer.start();
// 等待几秒,防止生产者启动未完成就发送消息
TimeUnit.SECONDS.sleep(3);

2.可能超时时间设置5秒太短了,可以设置长些

producer.setSendMsgTimeout(30000);

修改后代码如下:

public class SyncProducer {
    public static void main(String[] args) throws Exception {
       // 创建一个producer,参数为Producer Group名称
        DefaultMQProducer producer = new DefaultMQProducer("test");
        // 指定nameServer地址
        producer.setNamesrvAddr("192.168.124.10:9876");
        // 设置当发送失败时重试发送的次数,默认为2次
        producer.setRetryTimesWhenSendFailed(3);
        // 设置发送超时时限为5s,默认3s
        producer.setSendMsgTimeout(30000);
        // 开启生产者
        producer.start();
        // 等待几秒,防止生产者启动未完成就发送消息
        TimeUnit.SECONDS.sleep(3);
 
        for (int i = 0; i < 10; i++) {
            byte[] body = ("hello," + i).getBytes();
            Message msg = new Message("TopicTest", "TagA", body);
            // 发送消息
            SendResult sendResult = producer.send(msg);
            System.out.println(sendResult);
        }
        producer.shutdown();
    }
}

Logo

鸿蒙生态一站式服务平台。

更多推荐