阿里云MNS Queue Rest API操作示例

2023-10-21 05:40

本文主要是介绍阿里云MNS Queue Rest API操作示例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

概述

阿里云消息服务(Message Service)是一种高效、可靠、安全、便捷、可弹性扩展的分布式消息服务。MNS能够帮助应用开发者在他们应用的分布式组件上自由的传递数据、通知消息,构建松耦合系统。本文主要介绍基于Java 语言实现Queue的创建、删除以及消息的发送及接受的Rest API操作。

签名验证工具

如果在使用过程中因为签名问题一直无法通过,建议直接使用签名验证工具进行快速的测试验证。

_

Code Sample
创建队列
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.entity.StringEntity;import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URI;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;public class CreateMNSQueue {public static void main(String[] args) {//参数设置String AccessKeySecret = "********";//Access Key SecretString AccessKeyId = "********";//AccessKey IDString AccountId = "********";//Account ID//获取GMT英文格式时间Date d=new Date();DateFormat format=new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z",Locale.ENGLISH);//英文格式的时间转换时需要带上Locale.ENGLISH,否则会转换失败,因为它默认的是本地化的设置,除非你的操作系统是英文的,总之时间转换时需要时间格式与模式保持一致。format.setTimeZone(TimeZone.getTimeZone("GMT"));String date = format.format(d);String body = "<?xml version=\"1.0\" encoding=\"UTF-8\"  ?>\n" +"    <Queue xmlns=\"http://mns.aliyuncs.com/doc/v1/\">\n" +"    <VisibilityTimeout >60</VisibilityTimeout>\n" +"    <MaximumMessageSize>1024</MaximumMessageSize>\n" +"    <MessageRetentionPeriod>120</MessageRetentionPeriod>\n" +"    <DelaySeconds>0</DelaySeconds>\n" +"    </Queue>";//构造签名StringString SignString = "PUT\n" +"\n"+"application/xml"+"\n"+date + "\n"+"x-mns-version:2015-06-06" +"\n"+"/queues/TestQueue123";String sign = encode(AccessKeySecret,SignString);String Authorization = "MNS " + AccessKeyId + ":" + sign;HttpClient httpclient = HttpClients.createDefault();try{URIBuilder builder = new URIBuilder("http://" + AccountId + ".mns.cn-hangzhou.aliyuncs.com/queues/TestQueue123");//在杭州区域URI uri = builder.build();HttpPut request = new HttpPut(uri);request.setHeader("Authorization", Authorization);request.setHeader("Date", date);request.setHeader("Host", AccountId + ".mns.cn-hangzhou.aliyuncs.com");request.setHeader("Content-Type","application/xml");request.setHeader("x-mns-version","2015-06-06");// Request bodyStringEntity reqEntity = new StringEntity(body,"UTF-8");request.setEntity(reqEntity);HttpResponse response = httpclient.execute(request);HttpEntity entity = response.getEntity();if (entity != null){System.out.println(EntityUtils.toString(entity));}}catch (Exception e){System.out.println("error");System.out.println(e.getMessage());}}//写一个md5加密的方法public static String md5(String plainText) {//定义一个字节数组byte[] secretBytes = null;try {// 生成一个MD5加密计算摘要MessageDigest md = MessageDigest.getInstance("MD5");//对字符串进行加密md.update(plainText.getBytes());//获得加密后的数据secretBytes = md.digest();} catch (NoSuchAlgorithmException e) {throw new RuntimeException("没有md5这个算法!");}//将加密后的数据转换为16进制数字String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字// 如果生成数字未满32位,需要前面补0for (int i = 0; i < 32 - md5code.length(); i++) {md5code = "0" + md5code;}return md5code;}//计算签名public static String encode(String accessKey, String data) {try {byte[] keyBytes = accessKey.getBytes("UTF-8");byte[] dataBytes = data.getBytes("UTF-8");Mac mac = Mac.getInstance("HmacSHA1");mac.init(new SecretKeySpec(keyBytes, "HmacSHA1"));return new String(Base64.encodeBase64(mac.doFinal(dataBytes)));} catch (UnsupportedEncodingException var5) {throw new RuntimeException("Not supported encoding method UTF-8", var5);} catch (NoSuchAlgorithmException var6) {throw new RuntimeException("Not supported signature method hmac-sha1", var6);} catch (InvalidKeyException var7) {throw new RuntimeException("Failed to calculate the signature", var7);}}
}
删除队列
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URI;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;public class DeleteMNSQueue {public static void main(String[] args) {//参数设置String AccessKeySecret = "********";//Access Key SecretString AccessKeyId = "********";//AccessKey IDString AccountId = "********";//获取GMT英文格式时间Date d=new Date();DateFormat format=new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z",Locale.ENGLISH);//英文格式的时间转换时需要带上Locale.ENGLISH,否则会转换失败,因为它默认的是本地化的设置,除非你的操作系统是英文的,总之时间转换时需要时间格式与模式保持一致。format.setTimeZone(TimeZone.getTimeZone("GMT"));String date = format.format(d);//构造签名StringString SignString = "DELETE\n" +"\n"+"\n"+date + "\n"+"x-mns-version:2015-06-06" +"\n"+"/queues/TestQueue123";String sign = encode(AccessKeySecret,SignString);String Authorization = "MNS " + AccessKeyId + ":" + sign;HttpClient httpclient = HttpClients.createDefault();try{URIBuilder builder = new URIBuilder("http://" + AccountId + ".mns.cn-hangzhou.aliyuncs.com/queues/TestQueue123");//在青岛区域创建ProjectURI uri = builder.build();HttpDelete request = new HttpDelete(uri);request.setHeader("Authorization", Authorization);request.setHeader("Date", date);request.setHeader("Host", AccountId + ".mns.cn-hangzhou.aliyuncs.com");request.setHeader("x-mns-version","2015-06-06");HttpResponse response = httpclient.execute(request);HttpEntity entity = response.getEntity();if (entity != null){System.out.println(EntityUtils.toString(entity));}}catch (Exception e){System.out.println("error");System.out.println(e.getMessage());}}//写一个md5加密的方法public static String md5(String plainText) {//定义一个字节数组byte[] secretBytes = null;try {// 生成一个MD5加密计算摘要MessageDigest md = MessageDigest.getInstance("MD5");//对字符串进行加密md.update(plainText.getBytes());//获得加密后的数据secretBytes = md.digest();} catch (NoSuchAlgorithmException e) {throw new RuntimeException("没有md5这个算法!");}//将加密后的数据转换为16进制数字String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字// 如果生成数字未满32位,需要前面补0for (int i = 0; i < 32 - md5code.length(); i++) {md5code = "0" + md5code;}return md5code;}//计算签名public static String encode(String accessKey, String data) {try {byte[] keyBytes = accessKey.getBytes("UTF-8");byte[] dataBytes = data.getBytes("UTF-8");Mac mac = Mac.getInstance("HmacSHA1");mac.init(new SecretKeySpec(keyBytes, "HmacSHA1"));return new String(Base64.encodeBase64(mac.doFinal(dataBytes)));} catch (UnsupportedEncodingException var5) {throw new RuntimeException("Not supported encoding method UTF-8", var5);} catch (NoSuchAlgorithmException var6) {throw new RuntimeException("Not supported signature method hmac-sha1", var6);} catch (InvalidKeyException var7) {throw new RuntimeException("Failed to calculate the signature", var7);}}
}
发送消息
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URI;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;public class SendMessageToMNSQueue {public static void main(String[] args) {//参数设置String AccessKeySecret = "******";//Access Key SecretString AccessKeyId = "******";//AccessKey IDString AccountId = "********";//获取GMT英文格式时间Date d=new Date();DateFormat format=new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z",Locale.ENGLISH);//英文格式的时间转换时需要带上Locale.ENGLISH,否则会转换失败,因为它默认的是本地化的设置,除非你的操作系统是英文的,总之时间转换时需要时间格式与模式保持一致。format.setTimeZone(TimeZone.getTimeZone("GMT"));String date = format.format(d);//延迟消息String body = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +"    <Message xmlns=\"http://mns.aliyuncs.com/doc/v1/\">\n" +"        <MessageBody>The Test Message!</MessageBody>\n" +"        <DelaySeconds>0</DelaySeconds>\n" +"        <Priority>1</Priority>\n" +"    </Message>";//构造签名StringString SignString = "POST\n" +"\n"+"text/xml;charset=utf-8"+"\n"+date + "\n"+"x-mns-version:2015-06-06" +"\n"+"/queues/TestQueue123/messages";String sign = encode(AccessKeySecret,SignString);String Authorization = "MNS " + AccessKeyId + ":" + sign;HttpClient httpclient = HttpClients.createDefault();try{URIBuilder builder = new URIBuilder("http://" + AccountId + ".mns.cn-hangzhou.aliyuncs.com/queues/TestQueue123/messages");URI uri = builder.build();HttpPost request = new HttpPost(uri);request.setHeader("Authorization", Authorization);request.setHeader("Date", date);request.setHeader("Host", AccountId + ".mns.cn-hangzhou.aliyuncs.com");request.setHeader("Content-Type","text/xml;charset=utf-8");request.setHeader("x-mns-version","2015-06-06");// Request bodyStringEntity reqEntity = new StringEntity(body,"UTF-8");request.setEntity(reqEntity);HttpResponse response = httpclient.execute(request);HttpEntity entity = response.getEntity();if (entity != null){System.out.println(EntityUtils.toString(entity));}}catch (Exception e){System.out.println("error");System.out.println(e.getMessage());}}//写一个md5加密的方法public static String md5(String plainText) {//定义一个字节数组byte[] secretBytes = null;try {// 生成一个MD5加密计算摘要MessageDigest md = MessageDigest.getInstance("MD5");//对字符串进行加密md.update(plainText.getBytes());//获得加密后的数据secretBytes = md.digest();} catch (NoSuchAlgorithmException e) {throw new RuntimeException("没有md5这个算法!");}//将加密后的数据转换为16进制数字String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字// 如果生成数字未满32位,需要前面补0for (int i = 0; i < 32 - md5code.length(); i++) {md5code = "0" + md5code;}return md5code;}//计算签名public static String encode(String accessKey, String data) {try {byte[] keyBytes = accessKey.getBytes("UTF-8");byte[] dataBytes = data.getBytes("UTF-8");Mac mac = Mac.getInstance("HmacSHA1");mac.init(new SecretKeySpec(keyBytes, "HmacSHA1"));return new String(Base64.encodeBase64(mac.doFinal(dataBytes)));} catch (UnsupportedEncodingException var5) {throw new RuntimeException("Not supported encoding method UTF-8", var5);} catch (NoSuchAlgorithmException var6) {throw new RuntimeException("Not supported signature method hmac-sha1", var6);} catch (InvalidKeyException var7) {throw new RuntimeException("Failed to calculate the signature", var7);}}
}
消费消息
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URI;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;public class GetMessageFromMNSQueue {public static void main(String[] args) {//参数设置String AccessKeySecret = "********";//Access Key SecretString AccessKeyId = "********";//AccessKey IDString AccountId = "********";//获取GMT英文格式时间Date d=new Date();DateFormat format=new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z",Locale.ENGLISH);//英文格式的时间转换时需要带上Locale.ENGLISH,否则会转换失败,因为它默认的是本地化的设置,除非你的操作系统是英文的,总之时间转换时需要时间格式与模式保持一致。format.setTimeZone(TimeZone.getTimeZone("GMT"));String date = format.format(d);//构造签名StringString SignString = "GET\n" +"\n"+"\n"+date + "\n"+"x-mns-version:2015-06-06" +"\n"+"/queues/TestQueue123/messages?waitseconds=30";String sign = encode(AccessKeySecret,SignString);String Authorization = "MNS " + AccessKeyId + ":" + sign;HttpClient httpclient = HttpClients.createDefault();try{URIBuilder builder = new URIBuilder("http://" + AccountId + ".mns.cn-hangzhou.aliyuncs.com/queues/TestQueue123/messages?waitseconds=30");URI uri = builder.build();HttpGet request = new HttpGet(uri);request.setHeader("Authorization", Authorization);request.setHeader("Date", date);request.setHeader("Host", AccountId + ".mns.cn-hangzhou.aliyuncs.com");request.setHeader("x-mns-version","2015-06-06");HttpResponse response = httpclient.execute(request);HttpEntity entity = response.getEntity();if (entity != null){System.out.println(EntityUtils.toString(entity));}}catch (Exception e){System.out.println("error");System.out.println(e.getMessage());}}//写一个md5加密的方法public static String md5(String plainText) {//定义一个字节数组byte[] secretBytes = null;try {// 生成一个MD5加密计算摘要MessageDigest md = MessageDigest.getInstance("MD5");//对字符串进行加密md.update(plainText.getBytes());//获得加密后的数据secretBytes = md.digest();} catch (NoSuchAlgorithmException e) {throw new RuntimeException("没有md5这个算法!");}//将加密后的数据转换为16进制数字String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字// 如果生成数字未满32位,需要前面补0for (int i = 0; i < 32 - md5code.length(); i++) {md5code = "0" + md5code;}return md5code;}//计算签名public static String encode(String accessKey, String data) {try {byte[] keyBytes = accessKey.getBytes("UTF-8");byte[] dataBytes = data.getBytes("UTF-8");Mac mac = Mac.getInstance("HmacSHA1");mac.init(new SecretKeySpec(keyBytes, "HmacSHA1"));return new String(Base64.encodeBase64(mac.doFinal(dataBytes)));} catch (UnsupportedEncodingException var5) {throw new RuntimeException("Not supported encoding method UTF-8", var5);} catch (NoSuchAlgorithmException var6) {throw new RuntimeException("Not supported signature method hmac-sha1", var6);} catch (InvalidKeyException var7) {throw new RuntimeException("Failed to calculate the signature", var7);}}
}
更多参考

签名验证工具
RESTfulAPI概述

备注: 示例代码仅供快速测试使用,未做冗余处理。

这篇关于阿里云MNS Queue Rest API操作示例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/252315

相关文章

Mysql表的简单操作(基本技能)

《Mysql表的简单操作(基本技能)》在数据库中,表的操作主要包括表的创建、查看、修改、删除等,了解如何操作这些表是数据库管理和开发的基本技能,本文给大家介绍Mysql表的简单操作,感兴趣的朋友一起看... 目录3.1 创建表 3.2 查看表结构3.3 修改表3.4 实践案例:修改表在数据库中,表的操作主要

C# WinForms存储过程操作数据库的实例讲解

《C#WinForms存储过程操作数据库的实例讲解》:本文主要介绍C#WinForms存储过程操作数据库的实例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、存储过程基础二、C# 调用流程1. 数据库连接配置2. 执行存储过程(增删改)3. 查询数据三、事务处

Java中StopWatch的使用示例详解

《Java中StopWatch的使用示例详解》stopWatch是org.springframework.util包下的一个工具类,使用它可直观的输出代码执行耗时,以及执行时间百分比,这篇文章主要介绍... 目录stopWatch 是org.springframework.util 包下的一个工具类,使用它

Java使用Curator进行ZooKeeper操作的详细教程

《Java使用Curator进行ZooKeeper操作的详细教程》ApacheCurator是一个基于ZooKeeper的Java客户端库,它极大地简化了使用ZooKeeper的开发工作,在分布式系统... 目录1、简述2、核心功能2.1 CuratorFramework2.2 Recipes3、示例实践3

Spring Boot 3.4.3 基于 Spring WebFlux 实现 SSE 功能(代码示例)

《SpringBoot3.4.3基于SpringWebFlux实现SSE功能(代码示例)》SpringBoot3.4.3结合SpringWebFlux实现SSE功能,为实时数据推送提供... 目录1. SSE 简介1.1 什么是 SSE?1.2 SSE 的优点1.3 适用场景2. Spring WebFlu

Java利用JSONPath操作JSON数据的技术指南

《Java利用JSONPath操作JSON数据的技术指南》JSONPath是一种强大的工具,用于查询和操作JSON数据,类似于SQL的语法,它为处理复杂的JSON数据结构提供了简单且高效... 目录1、简述2、什么是 jsONPath?3、Java 示例3.1 基本查询3.2 过滤查询3.3 递归搜索3.4

springboot security快速使用示例详解

《springbootsecurity快速使用示例详解》:本文主要介绍springbootsecurity快速使用示例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝... 目录创www.chinasem.cn建spring boot项目生成脚手架配置依赖接口示例代码项目结构启用s

golang 日志log与logrus示例详解

《golang日志log与logrus示例详解》log是Go语言标准库中一个简单的日志库,本文给大家介绍golang日志log与logrus示例详解,感兴趣的朋友一起看看吧... 目录一、Go 标准库 log 详解1. 功能特点2. 常用函数3. 示例代码4. 优势和局限二、第三方库 logrus 详解1.

SpringBoot实现MD5加盐算法的示例代码

《SpringBoot实现MD5加盐算法的示例代码》加盐算法是一种用于增强密码安全性的技术,本文主要介绍了SpringBoot实现MD5加盐算法的示例代码,文中通过示例代码介绍的非常详细,对大家的学习... 目录一、什么是加盐算法二、如何实现加盐算法2.1 加盐算法代码实现2.2 注册页面中进行密码加盐2.

基于Flask框架添加多个AI模型的API并进行交互

《基于Flask框架添加多个AI模型的API并进行交互》:本文主要介绍如何基于Flask框架开发AI模型API管理系统,允许用户添加、删除不同AI模型的API密钥,感兴趣的可以了解下... 目录1. 概述2. 后端代码说明2.1 依赖库导入2.2 应用初始化2.3 API 存储字典2.4 路由函数2.5 应