全部产品
Search
文档中心

云消息队列 RocketMQ 版:调用TCP协议的SDK收发普通消息

更新时间:Jan 30, 2024

在控制台创建完所有资源之后,您可以调用云消息队列 RocketMQ 版的TCP协议的SDK收发普通消息。

前提条件

  • 创建资源

    说明

    本文以普通消息为例进行说明,因此您创建的普通消息的Topic不能用来收发其他类型的消息,包括定时、延时、顺序和事务消息。换言之,切勿混用不同消息类型的Topic。

  • 创建AccessKey

下载并安装TCP协议的SDK

说明

商业版SDK和社区版SDK相比,提供了更加丰富的功能特性并具有更高的稳定性保障,推荐您使用阿里云云消息队列 RocketMQ 版商业版SDK进行接入。社区版SDK仅在开源RocketMQ迁移上云且不希望修改代码时使用。

云消息队列 RocketMQ 版提供了以下商业版TCP协议的SDK,请按需获取相应语言的客户端SDK。

调用TCP协议的SDK发送普通消息

获取相应语言的客户端SDK后,您即可运行以下示例代码发送普通消息。

Java

import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.OnExceptionContext;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.SendCallback;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.PropertyKeyConst;

import java.util.Properties;

public class ProducerTest {
    public static void main(String[] args) {
        Properties properties = new Properties();
        // AccessKey ID,阿里云身份验证标识。获取方式,请参见本文前提条件中的获取AccessKey。
        properties.put(PropertyKeyConst.AccessKey, "XXX");
        // AccessKey Secret,阿里云身份验证密钥。获取方式,请参见本文前提条件中的获取AccessKey。
        properties.put(PropertyKeyConst.SecretKey, "XXX");
        //设置发送超时时间,单位毫秒。
        properties.setProperty(PropertyKeyConst.SendMsgTimeoutMillis, "3000");
        // 设置TCP协议接入点,进入控制台的实例详情页面的TCP协议客户端接入点区域查看。
        properties.put(PropertyKeyConst.NAMESRV_ADDR,
          "XXX");

        Producer producer = ONSFactory.createProducer(properties);
        // 在发送消息前,必须调用start方法来启动Producer,只需调用一次即可。
        producer.start();

        Message msg = new Message(
                // Message所属的Topic。
                "TopicTestMQ",
                // Message Tag,可理解为Gmail中的标签,对消息进行再归类,方便Consumer指定过滤条件在消息队列RocketMQ版的服务器过滤。
                "TagA",
                // Message Body,任何二进制形式的数据,消息队列RocketMQ版不做任何干预,需要Producer与Consumer协商好一致的序列化和反序列化方式。
                "Hello MQ".getBytes());

        // 设置代表消息的业务关键属性,请尽可能全局唯一。以方便您在无法正常收到消息情况下,可通过控制台查询消息并补发。
        // 注意:不设置也不会影响消息正常收发。
        msg.setKey("ORDERID_100");

        // 异步发送消息,发送结果通过callback返回给客户端。
        producer.sendAsync(msg, new SendCallback() {
            @Override
            public void onSuccess(final SendResult sendResult) {
                // 消息发送成功。
                System.out.println("send message success. topic=" + sendResult.getTopic() + ", msgId=" + sendResult.getMessageId());
            }

            @Override
            public void onException(OnExceptionContext context) {
                // 消息发送失败,需要进行重试处理,可重新发送这条消息或持久化这条数据进行补偿处理。
                System.out.println("send message failed. topic=" + context.getTopic() + ", msgId=" + context.getMessageId());
            }
        });

        // 在callback返回之前即可取得msgId。
        System.out.println("send message async. topic=" + msg.getTopic() + ", msgId=" + msg.getMsgID());

        // 在应用退出前,销毁Producer对象。 注意:如果不销毁也没有问题。
        producer.shutdown();
    }
}                      

.NET

using System;
using ons;

public class ProducerExampleForEx
{
    public ProducerExampleForEx()
    {
    }

    static void Main(string[] args) {
        // 配置账号,从控制台获取设置。
        ONSFactoryProperty factoryInfo = new ONSFactoryProperty();
        // AccessKey ID,阿里云身份验证标识。获取方式,请参见本文前提条件中的获取AccessKey。
        factoryInfo.setFactoryProperty(ONSFactoryProperty.AccessKey, "Your access key");
        // AccessKey Secret,阿里云身份验证密钥。获取方式,请参见本文前提条件中的获取AccessKey。

        factoryInfo.setFactoryProperty(ONSFactoryProperty.SecretKey, "Your access secret");
        // 您在控制台创建的Group ID。
        factoryInfo.setFactoryProperty(ONSFactoryProperty.ProducerId, "GID_example");
        // 您在控制台创建的Topic。
        factoryInfo.setFactoryProperty(ONSFactoryProperty.PublishTopics, "T_example_topic_name");
        // 设置TCP协议接入点,进入控制台的实例详情页面的TCP协议客户端接入点区域查看。
        factoryInfo.setFactoryProperty(ONSFactoryProperty.NAMESRV_ADDR, "NameSrv_Addr");
        // 设置日志路径。
        factoryInfo.setFactoryProperty(ONSFactoryProperty.LogPath, "C://log");

        // 创建生产者实例。
        // 说明:生产者实例是线程安全的,可用于发送不同Topic的消息。基本上,您每一个线程只需要一个生产者实例。
        Producer producer = ONSFactory.getInstance().createProducer(factoryInfo);

        // 启动客户端实例。
        producer.start();

        // 创建消息对象。
        Message msg = new Message(factoryInfo.getPublishTopics(), "tagA", "Example message body");
        msg.setKey(Guid.NewGuid().ToString());
        for (int i = 0; i < 32; i++) {
            try
            {
                SendResultONS sendResult = producer.send(msg);
                Console.WriteLine("send success {0}", sendResult.getMessageId());
            }
            catch (Exception ex)
            {
                Console.WriteLine("send failure{0}", ex.ToString());
            }
        }

        // 在您的线程即将退出时,关闭生产者实例。
        producer.shutdown();

    }
}

C/C++

#include "ONSFactory.h"
#include "ONSClientException.h"

using namespace ons;

int main()
{

    //创建Producer,并配置发送消息所必需的信息。
    ONSFactoryProperty factoryInfo;
    factoryInfo.setFactoryProperty(ONSFactoryProperty::ProducerId, "XXX");//您在控制台创建的Group ID。
    factoryInfo.setFactoryProperty(ONSFactoryProperty::NAMESRV_ADDR, "XXX"); //设置TCP协议接入点,进入控制台的实例详情页面的TCP协议客户端接入点区域查看。
    factoryInfo.setFactoryProperty(ONSFactoryProperty::PublishTopics,"XXX" );// 在控制台创建的Topic。
    factoryInfo.setFactoryProperty(ONSFactoryProperty::MsgContent, "XXX");//消息内容。
    factoryInfo.setFactoryProperty(ONSFactoryProperty::AccessKey, "XXX");// AccessKey ID,阿里云身份验证标识。获取方式,请参见本文前提条件中的获取AccessKey。
    factoryInfo.setFactoryProperty(ONSFactoryProperty::SecretKey, "XXX" );// AccessKey Secret,阿里云身份验证密钥。获取方式,请参见本文前提条件中的获取AccessKey。


    //create producer;
    Producer *pProducer = ONSFactory::getInstance()->createProducer(factoryInfo);

    //在发送消息前,必须调用start方法来启动Producer,只需调用一次即可。
    pProducer->start();

    Message msg(
            //Message Topic
            factoryInfo.getPublishTopics(),
            //Message Tag,可理解为Gmail中的标签,对消息进行再归类,方便Consumer指定过滤条件在消息队列RocketMQ版的服务器过滤。
            "TagA",
            //Message Body,不能为空,消息队列RocketMQ版不做任何干预,需要Producer与Consumer协商好一致的序列化和反序列化方式。
            factoryInfo.getMessageContent()
    );

    // 设置代表消息的业务关键属性,请尽可能全局唯一。
    // 以方便您在无法正常收到消息情况下,可通过控制台查询消息并补发。
    // 注意:不设置也不会影响消息正常收发。
    msg.setKey("ORDERID_100");

    //发送消息,只要不抛出异常,就代表发送成功。
    try
    {
        SendResultONS sendResult = pProducer->send(msg);
    }
    catch(ONSClientException & e)
    {
        //自定义处理exception的细节。
    }
    // 在应用退出前,必须销毁Producer对象,否则会导致内存泄露等问题。
    pProducer->shutdown();

    return 0;
}

同时,您也可以在控制台页面,找到您创建的Topic,在其操作列,单击更多,在下拉列表中,选择快速体验,按需通过控制台或Docker快速体验。

查看消息是否发送成功

消息发送后,您可以在云消息队列 RocketMQ 版控制台查看消息发送状态,步骤如下:

  1. 在实例所在页面的左侧导航栏,单击消息查询
  2. 消息查询页面,按需选择查询条件,单击查询

    存储时间表示云消息队列 RocketMQ 版服务端存储这条消息的时间。如果查询到此信息,表示消息已经成功发送到服务端。

重要 此步骤演示的是第一次使用云消息队列 RocketMQ 版的场景,此时消费者从未启动过,所以消息状态显示暂无消费数据。要启动消费者并进行消息订阅请继续下一步操作订阅消息。更多消息状态请参见消息查询查询消息轨迹

调用TCP协议的SDK订阅普通消息

消息发送成功后,需要启动消费者来订阅普通消息。请按需运行对应语言的示例代码来启动消费者,并测试订阅消息的功能。请按照说明正确设置相关参数。

Java

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Consumer;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.PropertyKeyConst;

import java.util.Properties;

public class ConsumerTest {
   public static void main(String[] args) {
       Properties properties = new Properties();
        // 您在控制台创建的Group ID。
       properties.put(PropertyKeyConst.GROUP_ID, "XXX");
        // AccessKey ID,阿里云身份验证标识。获取方式,请参见本文前提条件中的获取AccessKey。
       properties.put(PropertyKeyConst.AccessKey, "XXX");
        // AccessKey Secret,阿里云身份验证密钥。获取方式,请参见本文前提条件中的获取AccessKey。
       properties.put(PropertyKeyConst.SecretKey, "XXX");
        // 设置TCP协议接入点,进入控制台的实例详情页面的TCP协议客户端接入点区域查看。
       properties.put(PropertyKeyConst.NAMESRV_ADDR,
         "XXX");
          // 集群订阅方式(默认)。
          // properties.put(PropertyKeyConst.MessageModel, PropertyValueConst.CLUSTERING);
          // 广播订阅方式。
          // properties.put(PropertyKeyConst.MessageModel, PropertyValueConst.BROADCASTING);

       Consumer consumer = ONSFactory.createConsumer(properties);
       consumer.subscribe("TopicTestMQ", "TagA||TagB", new MessageListener() { //订阅多个Tag
           public Action consume(Message message, ConsumeContext context) {
               System.out.println("Receive: " + message);
               return Action.CommitMessage;
           }
       });

        //订阅另外一个Topic,如需取消订阅该Topic,请删除该部分的订阅代码,重新启动消费端即可。
        consumer.subscribe("TopicTestMQ-Other", "*", new MessageListener() { //订阅全部Tag。
           public Action consume(Message message, ConsumeContext context) {
               System.out.println("Receive: " + message);
               return Action.CommitMessage;
           }
       });

       consumer.start();
       System.out.println("Consumer Started");
   }
}                 

.NET

using System;
using System.Threading;
using System.Text;
using ons;

// 从Broker拉取消息时要执行的回调函数。
public class MyMsgListener : MessageListener
{
    public MyMsgListener()
    {
    }

    ~MyMsgListener()
    {
    }

    public override ons.Action consume(Message value, ConsumeContext context)
    {
        Byte[] text = Encoding.Default.GetBytes(value.getBody());
        Console.WriteLine(Encoding.UTF8.GetString(text));
        return ons.Action.CommitMessage;
    }
}

public class ConsumerExampleForEx
{
    public ConsumerExampleForEx()
    {
    }

    static void Main(string[] args) {
        // 配置您的账号,以下设置均可从控制台获取。
        ONSFactoryProperty factoryInfo = new ONSFactoryProperty();
        // AccessKey ID,阿里云身份验证标识。获取方式,请参见本文前提条件中的获取AccessKey。
        factoryInfo.setFactoryProperty(ONSFactoryProperty.AccessKey, "Your access key");
        // AccessKey Secret,阿里云身份验证密钥。获取方式,请参见本文前提条件中的获取AccessKey。
        factoryInfo.setFactoryProperty(ONSFactoryProperty.SecretKey, "Your access secret");
        // 您在控制台创建的Group ID
        factoryInfo.setFactoryProperty(ONSFactoryProperty.ConsumerId, "GID_example");
        // 您在控制台创建的Topic。
        factoryInfo.setFactoryProperty(ONSFactoryProperty.PublishTopics, "T_example_topic_name");
        // 设置TCP协议接入点,进入控制台的实例详情页面的TCP协议客户端接入点区域查看。
        factoryInfo.setFactoryProperty(ONSFactoryProperty.NAMESRV_ADDR, "NameSrv_Addr");
        // 设置日志路径。
        factoryInfo.setFactoryProperty(ONSFactoryProperty.LogPath, "C://log");
        // 集群消费。
        // factoryInfo.setFactoryProperty(ONSFactoryProperty:: MessageModel, ONSFactoryProperty.CLUSTERING);
        // 广播消费。
        // factoryInfo.setFactoryProperty(ONSFactoryProperty:: MessageModel, ONSFactoryProperty.BROADCASTING);

        // 创建消费者实例。
        PushConsumer consumer = ONSFactory.getInstance().createPushConsumer(factoryInfo);

        // 订阅Topics。
        consumer.subscribe(factoryInfo.getPublishTopics(), "*", new MyMsgListener());

        // 启动客户端实例。
        consumer.start();

        //该设置仅供Demo使用,实际生产中请保证进程不退出。
        Thread.Sleep(300000);

        // 在进程即将退出时,关闭消费者实例。
        consumer.shutdown();
    }
}                               

C/C++

#include "ONSFactory.h"
using namespace ons;

// MyMsgListener:创建消费消息的实例。
//pushConsumer拉取到消息后,会主动调用该实例的consumer函数。
class MyMsgListener : public MessageListener
{

    public:

        MyMsgListener()
        {
        }

        virtual ~MyMsgListener()
        {
        }

        virtual Action consume(Message &message, ConsumeContext &context)
        {
            //自定义消息处理细节。
            return CommitMessage; //CONSUME_SUCCESS;
        }
};


int main(int argc, char* argv[])
{

    //pushConsumer创建和工作需要的参数,必须输入。
    ONSFactoryProperty factoryInfo;
    factoryInfo.setFactoryProperty(ONSFactoryProperty::ConsumerId, "XXX");//您在控制台创建的Group ID。
    factoryInfo.setFactoryProperty(ONSFactoryProperty::NAMESRV_ADDR, "XXX"); //设置TCP协议接入点,进入控制台的实例详情页面的TCP协议客户端接入点区域查看。
    factoryInfo.setFactoryProperty(ONSFactoryProperty::PublishTopics,"XXX" );//您在控制台创建的Topic。
    factoryInfo.setFactoryProperty(ONSFactoryProperty::AccessKey, "XXX");//AccessKey ID,阿里云身份验证标识。获取方式,请参见本文前提条件中的获取AccessKey。
    factoryInfo.setFactoryProperty(ONSFactoryProperty::SecretKey,  "XXX");//AccessKey Secret,阿里云身份验证密钥。获取方式,请参见本文前提条件中的获取AccessKey。
      // 集群订阅方式(默认)。
      // factoryInfo.setFactoryProperty(ONSFactoryProperty:: MessageModel, ONSFactoryProperty::CLUSTERING);
      // 广播订阅方式。
      // factoryInfo.setFactoryProperty(ONSFactoryProperty:: MessageModel, ONSFactoryProperty::BROADCASTING);

    //create pushConsumer
    PushConsumer* pushConsumer = ONSFactory::getInstance()->createPushConsumer(factoryInfo);

    //指定pushConsumer订阅的消息Topic和Tag,注册消息回调函数。
    MyMsgListener  msglistener;
    pushConsumer->subscribe(factoryInfo.getPublishTopics(), "*",&msglistener );

    //start pushConsumer
    pushConsumer->start();

    //注意:直到不再接收消息,才能调用shutdown;调用shutdown之后,Consumer退出,不能接收到任何消息。

    //销毁pushConsumer,在应用退出前,必须销毁Consumer对象,否则会导致内存泄露等问题。
    pushConsumer->shutdown();
    return 0;

}

查看消息是否订阅成功

  1. 在实例所在页面的左侧导航栏,单击Group 管理
  2. Group 管理页面,单击TCP 协议页签。
  3. 找到要查看的Group ID,在其操作列,单击详情
    消费者状态显示为在线,且订阅关系一致,说明订阅成功。