發(fā)送消息示例
更新時(shí)間:
本文介紹如何使用Java SDK向SMQ的指定主題中發(fā)布消息。
前提條件
消息體編碼選擇
當(dāng)消息體無(wú)特殊字符時(shí),建議您不使用Base64編碼。
發(fā)送消息時(shí)使用
message.setMessageBodyAsRawString
方法設(shè)置消息體。接收消息時(shí)使用
meesage.getMessageBodyAsRawString
方法獲取消息體。
示例代碼
示例代碼下載,請(qǐng)參見(jiàn)PublishMessageDemo。
import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.CloudTopic;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.common.utils.ServiceSettings;
import com.aliyun.mns.model.Base64TopicMessage;
import com.aliyun.mns.model.RawTopicMessage;
import com.aliyun.mns.model.TopicMessage;
/**
* 1. 遵循阿里云規(guī)范,env設(shè)置ak、sk。
* 2. ${"user.home"}/.aliyun-mns.properties 文件配置如下:
* mns.endpoint=http://xxxxxxx
* mns.msgBodyBase64Switch=true/false
*/
public class PublishMessageDemo {
private static final Boolean IS_BASE64 = Boolean.valueOf(ServiceSettings.getMNSPropertyValue("msgBodyBase64Switch","false"));
public static void main(String[] args) {
String topicName = "TestTopic";
String message = "hello world!";
CloudAccount account = new CloudAccount(ServiceSettings.getMNSAccountEndpoint());
//this client need only initialize once
MNSClient client = account.getMNSClient();
publishMsg(client, topicName, message);
client.close();
}
private static void publishMsg(MNSClient client, String topicName, String message) {
CloudTopic topic = client.getTopicRef(topicName);
TopicMessage msg = IS_BASE64 ? new Base64TopicMessage() : new RawTopicMessage();
try {
msg.setMessageBody(message);
// 可選。設(shè)置該條發(fā)布消息的filterTag
//msg.setMessageTag("filterTag");
TopicMessage publishResultMsg = topic.publishMessage(msg);
System.out.println("message publish.");
System.out.println("reqId:"+publishResultMsg.getRequestId());
System.out.println("msgId:"+publishResultMsg.getMessageId());
System.out.println("md5:"+publishResultMsg.getMessageBodyMD5());
} catch (Exception e) {
e.printStackTrace();
System.out.println("publishMsg error");
}
}
}
文檔內(nèi)容是否對(duì)您有幫助?