概述
阿里云消息服务(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 Secret
String AccessKeyId = "********";//AccessKey ID
String 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>";
//构造签名String
String 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 body
StringEntity 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位,需要前面补0
for (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 Secret
String AccessKeyId = "********";//AccessKey ID
String 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
String 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");//在青岛区域创建Project
URI 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位,需要前面补0
for (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 Secret
String AccessKeyId = "******";//AccessKey ID
String 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>";
//构造签名String
String 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 body
StringEntity 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位,需要前面补0
for (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 Secret
String AccessKeyId = "********";//AccessKey ID
String 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
String 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位,需要前面补0
for (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);
}
}
}
更多参考
备注: 示例代码仅供快速测试使用,未做冗余处理。