551
阿裏雲
Java 收發消息__HTTP 接入(簡單)_消息隊列 MQ-阿裏雲
本文主要描述如何在 Java 環境下使用 HTTP 協議收發 MQ 消息。
1. 準備環境
在工程 POM 文件添加 HTTP Java 客戶端的依賴。
<dependency><groupId>org.eclipse.jetty</groupId><artifactId>jetty-client</artifactId><version>9.3.4.RC1</version></dependency><dependency><groupId>com.aliyun.openservices</groupId><artifactId>ons-client</artifactId><version>1.1.11</version></dependency>
2. 運行代碼配置(user.properties)
您需要設置配置文件(user.properties)的相關內容,具體請參考申請 MQ 資源 。
[property]#您在控製台創建的TopicTopic=xxx#公測urlURL=https://publictest-rest.ons.aliyun.com#阿裏雲身份驗證碼Ak=xxx#阿裏雲身份驗證密鑰Sk=xxx#MQ控製台創建的Producer IDProducerID=xxx#MQ控製台創建的Consumer IDConsumerID=xxx
說明:
URL 中的 Key,Tag以及 POST Content-Type 沒有任何的限製,隻要確保Key 和 Tag 相同唯一即可,可以放在 user.properties 裏麵。
3. HTTP 發送消息示例代碼
您可以按以下說明設置相應參數並測試 HTTP 消息發送功能。
package com.aliyun.openservice.ons.http.demo;import java.nio.charset.Charset;import java.util.Date;import java.util.Properties;import org.eclipse.jetty.client.HttpClient;import org.eclipse.jetty.client.api.ContentProvider;import org.eclipse.jetty.client.api.ContentResponse;import org.eclipse.jetty.client.api.Request;import org.eclipse.jetty.client.util.StringContentProvider;import com.aliyun.openservices.ons.api.impl.authority.AuthUtil;public class HttpProducer {public static String SIGNATURE="Signature";public static String NUM="num";public static String CONSUMERID="ConsumerID";public static String PRODUCERID="ProducerID";public static String TIMEOUT="timeout";public static String TOPIC="Topic";public static String AK="AccessKey";public static String BODY="body";public static String MSGHANDLE="msgHandle";public static String TIME="time";public static void main(String[] args) throws Exception {HttpClient httpClient=new HttpClient();httpClient.setMaxConnectionsPerDestination(1);httpClient.start();Properties properties=new Properties();properties.load(HttpProducer.class.getClassLoader().getResourceAsStream("user.properties"));String topic=properties.getProperty("Topic"); //請在user.properties配置您的TopicString url=properties.getProperty("URL");//公測集群配置為https://publictest-rest.ons.aliyun.com/String ak=properties.getProperty("Ak");//請在user.properties配置您的AkString sk=properties.getProperty("Sk");//請在user.properties配置您的SkString pid=properties.getProperty("ProducerID");//請在user.properties配置您的Producer IDString date=String.valueOf(new Date().getTime());String sign=null;String body="hello ons http";String NEWLINE="n";String signString;for (int i = 0; i < 10; i++) {date=String.valueOf(new Date().getTime());Request req=httpClient.POST(url+"message/?topic="+topic+"&time="+date+"&tag=http"+"&key=http");ContentProvider content=new StringContentProvider(body);req.content(content);signString=topic+NEWLINE+pid+NEWLINE+MD5.getInstance().getMD5String(body)+NEWLINE+date;System.out.println(signString);sign=AuthUtil.calSignature(signString.getBytes(Charset.forName("UTF-8")), sk);req.header(SIGNATURE, sign);req.header(AK, ak);req.header(PRODUCERID, pid);ContentResponse response;response=req.send();System.out.println("send msg:"+response.getStatus()+response.getContentAsString());}}}
4. HTTP接收消息示例代碼
請按以下說明設置相應參數並測試 HTTP 消息接收功能。
package com.aliyun.openservice.ons.http.demo;import java.nio.charset.Charset;import java.util.Date;import java.util.List;import java.util.Properties;import org.eclipse.jetty.client.HttpClient;import org.eclipse.jetty.client.api.ContentProvider;import org.eclipse.jetty.client.api.ContentResponse;import org.eclipse.jetty.client.api.Request;import org.eclipse.jetty.client.util.StringContentProvider;import org.eclipse.jetty.http.HttpMethod;import com.alibaba.fastjson.JSON;import com.aliyun.openservice.ons.mqtt.demo.MqttProducer;import com.aliyun.openservices.ons.api.impl.authority.AuthUtil;public class HttpConsumer {public static String SIGNATURE="Signature";public static String NUM="num";public static String CONSUMERID="ConsumerID";public static String PRODUCERID="ProducerID";public static String TIMEOUT="timeout";public static String TOPIC="Topic";public static String AK="AccessKey";public static String BODY="body";public static String MSGHANDLE="msgHandle";public static String TIME="time";public static void main(String[] args) throws Exception {HttpClient httpClient=new HttpClient();httpClient.setMaxConnectionsPerDestination(1);httpClient.start();Properties properties=new Properties();properties.load(HttpConsumer.class.getClassLoader().getResourceAsStream("user.properties"));String topic=properties.getProperty("Topic"); //請在user.properties配置您的topicString url=properties.getProperty("URL");//公測集群配置為https://publictest-rest.ons.aliyun.com/String ak=properties.getProperty("Ak");//請在user.properties配置您的AkString sk=properties.getProperty("Sk");//請在user.properties配置您的SkString cid=properties.getProperty("ConsumerID");//請在user.properties配置您的Consumer IDString date=String.valueOf(new Date().getTime());String sign=null;String NEWLINE="n";String signString;System.out.println(NEWLINE+NEWLINE);while (true) {try {date=String.valueOf(new Date().getTime());Request req=httpClient.POST(url+"message/?topic="+topic+"&time="+date+"&num="+32);req.method(HttpMethod.GET);ContentResponse response;signString=topic+NEWLINE+cid+NEWLINE+date;sign=AuthUtil.calSignature(signString.getBytes(Charset.forName("UTF-8")), sk);req.header(SIGNATURE, sign);req.header(AK, ak);req.header(CONSUMERID, cid);long start=System.currentTimeMillis();response=req.send();System.out.println("get cost:"+(System.currentTimeMillis()-start)/1000+" "+response.getStatus()+" "+response.getContentAsString());List<SimpleMessage> list = null;if (response.getContentAsString()!=null&&!response.getContentAsString().isEmpty()) {list=JSON.parseArray(response.getContentAsString(), SimpleMessage.class);}if (list==null||list.size()==0) {Thread.sleep(100);continue;}System.out.println("size is :"+list.size());for (SimpleMessage simpleMessage : list) {date=String.valueOf(new Date().getTime());System.out.println("receive msg:"+simpleMessage.getBody()+" born time "+simpleMessage.getBornTime());req=httpClient.POST(url+"message/?msgHandle="+simpleMessage.getMsgHandle()+"&topic="+topic+"&time="+date);req.method(HttpMethod.DELETE);signString=topic+NEWLINE+cid+NEWLINE+simpleMessage.getMsgHandle()+NEWLINE+date;sign=AuthUtil.calSignature(signString.getBytes(Charset.forName("UTF-8")), sk);req.header(SIGNATURE, sign);req.header(AK, ak);req.header(CONSUMERID, cid);response=req.send();System.out.println("delete msg:"+response.toString());}Thread.sleep(100);} catch (Exception e) {e.printStackTrace();}}}}
5. HTTP示例程序工具類
(1)消息封裝類: SimpleMessage.java
package com.aliyun.openservice.ons.http.demo;public class SimpleMessage {private String body;private String msgId;private String bornTime;private String msgHandle;private int reconsumeTimes;private String tag;public void setTag(String tag) {this.tag = tag;}public String getTag() {return tag;}public int getReconsumeTimes() {return reconsumeTimes;}public void setReconsumeTimes(int reconsumeTimes) {this.reconsumeTimes = reconsumeTimes;}public void setMsgHandle(String msgHandle) {this.msgHandle = msgHandle;}public String getMsgHandle() {return msgHandle;}public String getBody() {return body;}public void setBody(String body) {this.body = body;}public String getMsgId() {return msgId;}public void setMsgId(String msgId) {this.msgId = msgId;}public String getBornTime() {return bornTime;}public void setBornTime(String bornTime) {this.bornTime = bornTime;}}
(2)字符串簽名類: MD5.java
package com.aliyun.openservice.ons.http.demo;import java.io.UnsupportedEncodingException;import java.nio.charset.Charset;import java.security.MessageDigest;import java.sql.SQLException;import java.util.Date;import java.util.HashMap;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.locks.ReentrantLock;import org.slf4j.LoggerFactory;public class MD5 {private static final org.slf4j.Logger log = LoggerFactory.getLogger(MD5.class);private static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };private static Map<Character, Integer> rDigits = new HashMap<Character, Integer>(16);static {for (int i = 0; i < digits.length; ++i) {rDigits.put(digits[i], i);}}private static MD5 me = new MD5();private MessageDigest mHasher;private final ReentrantLock opLock = new ReentrantLock();private MD5() {try {this.mHasher = MessageDigest.getInstance("md5");} catch (Exception e) {throw new RuntimeException(e);}}public static MD5 getInstance() {return me;}public String getMD5String(String content) {return this.bytes2string(this.hash(content));}public String getMD5String(byte[] content) {return this.bytes2string(this.hash(content));}public byte[] getMD5Bytes(byte[] content) {return this.hash(content);}public byte[] hash(String str) {this.opLock.lock();try {byte[] bt = this.mHasher.digest(str.getBytes("utf-8"));if (null == bt || bt.length != 16) {throw new IllegalArgumentException("md5 need");}return bt;} catch (UnsupportedEncodingException e) {throw new RuntimeException("unsupported utf-8 encoding", e);} finally {this.opLock.unlock();}}public byte[] hash(byte[] data) {this.opLock.lock();try {byte[] bt = this.mHasher.digest(data);if (null == bt || bt.length != 16) {throw new IllegalArgumentException("md5 need");}return bt;} finally {this.opLock.unlock();}}public String bytes2string(byte[] bt) {int l = bt.length;char[] out = new char[l << 1];for (int i = 0, j = 0; i < l; i++) {out[j++] = digits[(0xF0 & bt[i]) >>> 4];out[j++] = digits[0x0F & bt[i]];}if (log.isDebugEnabled()) {log.debug("[hash]" + new String(out));}return new String(out);}public byte[] string2bytes(String str) {if (null == str) {throw new NullPointerException("Argument is not allowed empty");}if (str.length() != 32) {throw new IllegalArgumentException("String length must equals 32");}byte[] data = new byte[16];char[] chs = str.toCharArray();for (int i = 0; i < 16; ++i) {int h = rDigits.get(chs[i * 2]).intValue();int l = rDigits.get(chs[i * 2 + 1]).intValue();data[i] = (byte) ((h & 0x0F) << 4 | l & 0x0F);}return data;}}
最後更新:2016-11-23 16:04:13
上一篇:
HTTP 協議規範__HTTP 接入(簡單)_消息隊列 MQ-阿裏雲
下一篇:
PHP 收發消息__HTTP 接入(簡單)_消息隊列 MQ-阿裏雲
通過編排模板創建 WordPress__快速入門_容器服務-阿裏雲
刪除域名證書__域名相關接口_API_API 網關-阿裏雲
ECS被入侵處理__攻擊防護_Web 應用防火牆-阿裏雲
設置強製跳轉__配置操作接口_API 手冊_CDN-阿裏雲
授權__使用手冊(調用API)_API 網關-阿裏雲
功能實時性__常見問題_日誌服務-阿裏雲
公共請求參數__公共參數_API參考_彈性伸縮-阿裏雲
測試執行階段__性能測試流程體係_性能測試體係_性能測試-阿裏雲
發送請求示例代碼__API介紹_文字識別_人工智能圖像類-阿裏雲
推送通知給android__API列表_OpenAPI 1.0_移動推送-阿裏雲
相關內容
常見錯誤說明__附錄_大數據計算服務-阿裏雲
發送短信接口__API使用手冊_短信服務-阿裏雲
接口文檔__Android_安全組件教程_移動安全-阿裏雲
運營商錯誤碼(聯通)__常見問題_短信服務-阿裏雲
設置短信模板__使用手冊_短信服務-阿裏雲
OSS 權限問題及排查__常見錯誤及排除_最佳實踐_對象存儲 OSS-阿裏雲
消息通知__操作指南_批量計算-阿裏雲
設備端快速接入(MQTT)__快速開始_阿裏雲物聯網套件-阿裏雲
查詢API調用流量數據__API管理相關接口_API_API 網關-阿裏雲
使用STS訪問__JavaScript-SDK_SDK 參考_對象存儲 OSS-阿裏雲