使用 Amazon 软件开发工具包将短信发布到 Amazon SNS 主题
以下代码示例显示了如何:
创建 Amazon SNS 主题。
使用手机号码订阅主题。
向主题发布 SMS 消息,以使所有订阅的电话号码一次接收消息。
- Java
-
- SDK for Java 1.x
-
创建一个主题并返回其 ARN。
public static String createSNSTopic(AmazonSNSClient snsClient) { CreateTopicRequest createTopic = new CreateTopicRequest("mySNSTopic"); CreateTopicResult result = snsClient.createTopic(createTopic); System.out.println("Create topic request: " + snsClient.getCachedResponseMetadata(createTopic)); System.out.println("Create topic result: " + result); return result.getTopicArn(); }
为终端节点订阅主题。
public static void subscribeToTopic(AmazonSNSClient snsClient, String topicArn, String protocol, String endpoint) { SubscribeRequest subscribe = new SubscribeRequest(topicArn, protocol, endpoint); SubscribeResult subscribeResult = snsClient.subscribe(subscribe); System.out.println("Subscribe request: " + snsClient.getCachedResponseMetadata(subscribe)); System.out.println("Subscribe result: " + subscribeResult); }
设置消息的属性,例如发件人的 ID、最高价格及其类型。消息属性是可选的。
public static void addMessageAttributes(Map<String, MessageAttributeValue> smsAttributes) { smsAttributes.put("AWS.SNS.SMS.SenderID", new MessageAttributeValue() .withStringValue("mySenderID") //The sender ID shown on the device. .withDataType("String")); smsAttributes.put("AWS.SNS.SMS.MaxPrice", new MessageAttributeValue() .withStringValue("0.50") //Sets the max price to 0.50 USD. .withDataType("Number")); smsAttributes.put("AWS.SNS.SMS.SMSType", new MessageAttributeValue() .withStringValue("Promotional") //Sets the type to promotional. .withDataType("String")); }
向主题发布消息。消息将会发送到每个订阅者。
public static void sendSMSMessageToTopic(AmazonSNSClient snsClient, String topicArn, String message, Map<String, MessageAttributeValue> smsAttributes) { PublishResult result = snsClient.publish(new PublishRequest() .withTopicArn(topicArn) .withMessage(message) .withMessageAttributes(smsAttributes)); System.out.println(result); }
调用以前的函数以创建主题、订阅电话号码、设置消息属性以及向主题发布消息。
public static void main(String[] args) { AmazonSNSClient snsClient = new AmazonSNSClient(); String topicArn = createSNSTopic(snsClient); String phoneNumber = "+1XXX5550100"; // Specify a protocol of "sms" when subscribing a phone number. subscribeToTopic(snsClient, topicArn, "sms", phoneNumber); String message = "My SMS message"; Map<String, MessageAttributeValue> smsAttributes = new HashMap<String, MessageAttributeValue>(); addMessageAttributes(smsAttributes) sendSMSMessageToTopic(snsClient, topicArn, message, smsAttributes); }
-
在 GitHub
中查找说明和更多代码。
-
有关 Amazon 软件开发工具包开发人员指南和代码示例的完整列表,请参阅 将 Amazon SNS 与 Amazon 开发工具包结合使用。本主题还包括有关入门的信息以及有关先前的软件开发工具包版本的详细信息。
创建并发布到 FIFO 主题
发布大型消息