阿里云-消息隊(duì)列-HTTP接入手冊(cè)-D_第1頁(yè)
阿里云-消息隊(duì)列-HTTP接入手冊(cè)-D_第2頁(yè)
阿里云-消息隊(duì)列-HTTP接入手冊(cè)-D_第3頁(yè)
阿里云-消息隊(duì)列-HTTP接入手冊(cè)-D_第4頁(yè)
阿里云-消息隊(duì)列-HTTP接入手冊(cè)-D_第5頁(yè)
已閱讀5頁(yè),還剩24頁(yè)未讀 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶(hù)提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

1、消息隊(duì)列HTTP 接入(簡(jiǎn)單)消息隊(duì)列/HTTP 接入(簡(jiǎn)單)消息隊(duì)列/HTTP 接入(簡(jiǎn)單) PAGE 28 PAGE 28HTTP 接入(簡(jiǎn)單)MQ HTTP 接入簡(jiǎn)介HTTPMQHTTP 協(xié)議為載體,通過(guò)使用 HTTP 的常用接口來(lái)對(duì)消息隊(duì)列進(jìn)行增刪查。HTTP 接 入 優(yōu) 勢(shì)HTTP接入主要有以下幾大優(yōu)勢(shì):HTTP解決異構(gòu)網(wǎng)絡(luò)環(huán)境下的服務(wù)相互訪問(wèn)屏障,對(duì)于沒(méi)有提供相關(guān)操作消息隊(duì)列SDK的環(huán)境中,使用HTTP方式接入更為方便;消息隊(duì)列HTTP接入方式在使用上簡(jiǎn)單,上手快。HTTP 接入應(yīng)用場(chǎng)景HTTP 接入方式應(yīng)用的場(chǎng)景主要依托于客戶(hù)的業(yè)務(wù)場(chǎng)景,假設(shè)客戶(hù)的業(yè)務(wù)場(chǎng)景或者部分模塊是基于 HT

2、TP 協(xié)議并且需要通信服務(wù),就可以使用 MQPythonPHPHTTP 域名目前,HTTP 各 Region 域名如下。Region公網(wǎng)/內(nèi)網(wǎng)域名公網(wǎng)測(cè)試公網(wǎng)publictest- 華北2公網(wǎng)beijing-rest- 華北2內(nèi)網(wǎng)beijing-rest- 華東1公網(wǎng)hangzhou-rest- 華東1內(nèi)網(wǎng)hangzhou-rest- 華南1內(nèi)網(wǎng)shenzhen-rest- 華南1公網(wǎng)shenzhen-rest- 華東2內(nèi)網(wǎng)shanghai-rest- 華東2公網(wǎng)shanghai-rest- MQ HTTP 協(xié)議規(guī)范本文詳細(xì)介紹了 HTTP 協(xié)議相關(guān)的規(guī)范。域名字段說(shuō)明URL HYPERLIN

3、K http:/domain/message/ http:/domain/message/字段說(shuō)明URL HYPERLINK http:/domain/message/ http:/domain/message/MethodPOSTHEADERAccessKey : 阿里云身份驗(yàn)證;Signature 簽 名 : (signString=topic+n+pid+n+md5(Body)+n+time;Producer ID : 消息發(fā)布者IDParamTopic Time 時(shí)間戳(自1970-01-01, 00:00:00 GMT經(jīng)歷的毫秒數(shù),如果MQ收到時(shí)間戳已經(jīng)過(guò)了15s,那么會(huì)返回403)

4、Body消息體內(nèi)容為UTF-8編碼消息發(fā)送-ResponseStatus code說(shuō)明Body(json格式)201消息添加成功msgId:0A021F7300002A9 F0000000006531D6F,sendStatus:SEND_OK400請(qǐng)求失敗code:BODY_TOO_BIG,in fo:Message body size exceeds the upper limit of 64KB403鑒權(quán)失敗408請(qǐng)求超時(shí)消息接收-Request字段說(shuō)明URL HYPERLINK http:/domain/message/ http:/domain/message/MethodGETHE

5、ADERAccessKey : 阿里云AccessKeySignature 簽 名 : (signString=topic+n+ cid+n+time) Consumer ID : 消息訂閱者IDParamTopic Time 時(shí)間戳(自1970-01-01, 00:00:00 GMT經(jīng)歷的毫秒數(shù),如果MQ收到時(shí)間戳已經(jīng)過(guò)了15s,那么會(huì)返回403)消息接收-ResponseStatus code說(shuō)明Body(json格式)200消息讀取成功,會(huì)返回至多32條消息,如果沒(méi)有消息會(huì)循環(huán)遍歷事件直到有消息到來(lái)(poll模式),持續(xù)時(shí)間 30sbody:HelloMQ,bornTi me:14189

6、73464204,msgHandle:X1BFTkRJTkd NU0dfXyVSRVRSWSUkbG9uZ2ppJENJRF9sb25namlfdGxv bmdqaQ=, msgId:0A021F7300002A9F 000000000647076D,reconsumeTimes:1400請(qǐng)求失敗code:TOPIC_NOT_EXIST,info:topic not exist403鑒權(quán)失敗408請(qǐng)求超時(shí)消息刪除-Request字段說(shuō)明URL HYPERLINK http:/domain/message/ http:/domain/message/MethodDELETEHEADERAcces

7、sKey : 阿 里 云 AccessKey Signature 簽 名 : (signString=topic+n+cid+n+msgHandl e+n+timeConsumerId : 消息訂閱者IDParamTopic Time 時(shí)間戳(自1970-01-01, 00:00:00 GMT經(jīng)歷的毫秒數(shù),如果MQ收到時(shí)間戳已經(jīng)過(guò)了15s,那么會(huì)返回403) msgHandle 消息句柄消息刪除-ResponseStatus code說(shuō)明Body(json格式)204消息刪除成功,無(wú)需返回內(nèi)容400請(qǐng)求失敗code:TOPIC_NOT_EXIST,info:topic not exist403

8、鑒權(quán)失敗408請(qǐng)求超時(shí)Java 收發(fā)消息本文主要描述如何在 Java 環(huán)境下使用 HTTP 協(xié)議收發(fā) MQ 消息。準(zhǔn)備環(huán)境org.eclipse.jettyorg.eclipse.jettyjetty-client9.3.4.RC1com.aliyun.openservicesons-client1.1.11運(yùn)行代碼配置(perties)您需要設(shè)置配置文件(perties)的相關(guān)內(nèi)容,具體請(qǐng)參考申請(qǐng) MQ 資源 。propertyproperty#您在控制臺(tái)創(chuàng)建的Topic Topic=xxx#公測(cè)url HYPERLINK / URL=#阿里云身份驗(yàn)證碼Ak=xxx#阿里云身份驗(yàn)證密鑰Sk=

9、xxx#MQ控制臺(tái)創(chuàng)建的Producer ID ProducerID=xxx#MQ控制臺(tái)創(chuàng)建的Consumer ID ConsumerID=xxx說(shuō)明:URLKey,TagPOST Content-TypeKeyTpertiesHTTPpackage com.aliyun.openservice.ons.http.demo; import java.nio.charset.Charset;package com.aliyun.openservice.ons.http.demo; import java.nio.charset.Charset;import java.util.Date;impo

10、rt 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.opens

11、ervices.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; publ

12、ic 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();Prope

13、rties properties=new Properties(); properties.load(HttpProducer.class.getClassLoader().getResourceAsStream(perties); String topic=properties.getProperty(Topic); /請(qǐng)?jiān)趐erties配置您的TopicString HYPERLINK / url=properties.getProperty(URL);/公測(cè)集群配置為/String ak=properties.getProperty(Ak);/請(qǐng)?jiān)趐erties配置您的Ak String

14、 sk=properties.getProperty(Sk);/請(qǐng)?jiān)趐erties配置您的SkString pid=properties.getProperty(ProducerID);/請(qǐng)?jiān)趐erties配置您的Producer ID String 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 Dat

15、e().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);s

16、ign=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();HTTP接收消息示例代碼package co

17、m.aliyun.openservice.ons.http.demo; import java.nio.charset.Charset;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.Co

18、ntentProvider; 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.MqttProduc

19、er; 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 stat

20、ic 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

21、); httpClient.start();Properties properties=new Properties(); properties.load(HttpConsumer.class.getClassLoader().getResourceAsStream(perties); String topic=properties.getProperty(Topic); /請(qǐng)?jiān)趐erties配置您的topicString HYPERLINK / url=properties.getProperty(URL);/公測(cè)集群配置為/String ak=properties.getProperty(

22、Ak);/請(qǐng)?jiān)趐erties配置您的Ak String sk=properties.getProperty(Sk);/請(qǐng)?jiān)趐erties配置您的SkString cid=properties.getProperty(ConsumerID);/請(qǐng)?jiān)趐erties配置您的Consumer ID String date=String.valueOf(new Date().getTime();String sign=null; String NEWLINE=n; String signString;System.out.println(NEWLINE+NEWLINE); while (true) tr

23、y 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.heade

24、r(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 list = null;if (response.getContentAsString(

25、)!=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) for (SimpleMessage simpleMessage : list)

26、 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+

27、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

28、(Exception e) e.printStackTrace();HTTP示例程序工具類(lèi)package com.aliyun.openservice.ons.http.demo; public class SimpleMessage package com.aliyun.openservice.ons.http.demo; public class SimpleMessage private String body;private String msgId; private String bornTime; private String msgHandle; privateintrecons

29、umeTimes; private Stringtag;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.msgH

30、andle = msgHandle;public String getMsgHandle() return msgHandle;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 bornTi

31、me;public void setBornTime(String bornTime) this.bornTime = bornTime;package com.aliyun.openservice.ons.http.demo;import java.io.UnsupportedEncodingException; package com.aliyun.openservice.ons.http.demo;import java.io.UnsupportedEncodingException; import java.nio.charset.Charset;import java.securit

32、y.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 lo

33、g = LoggerFactory.getLogger(MD5.class);private static char digits = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f ;privatestaticMaprDigits=newHashMap(16); staticfor (int i = 0; i digits.length; +i) rDigits.put(digitsi, i);private static MD5 me = new MD5(); private MessageDigest mHasher;private fina

34、l 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 Stri

35、ng 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 IllegalArgumentE

36、xception(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 IllegalArgum

37、entException(md5 need);return bt; finally this.opLock.unlock();public String bytes2string(byte bt) int l = bt.length;char out = new charl 1;for (int i = 0, j = 0; i l; i+) for (int i = 0, j = 0; i 4; outj+ = digits0 x0F & bti;if (log.isDebugEnabled() log.debug(hash + new String(out);return new Strin

38、g(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 byte16; char chs = str.toCharArray(); for (int i = 0; i 16; +i) int h = r

39、Digits.get(chsi * 2).intValue();int l = rDigits.get(chsi * 2 + 1).intValue(); datai = (byte) (h & 0 x0F) 4 | l & 0 x0F);return data;PHP 收發(fā)消息本文描述如何在 PHP 環(huán)境下用 HTTP 協(xié)議收發(fā)消息。運(yùn)行環(huán)境準(zhǔn)備用 HTTP 協(xié)議發(fā)送或者接收消息,請(qǐng)完成以下準(zhǔn)備工作。WindowsIntelliJphpStorm HYPERLINK /phpstorm/download/index.html /phpstorm/download/index.htmlphpS

40、torm其他 IDE 開(kāi)發(fā)環(huán)境安裝步驟與此類(lèi)似。Linux/Unix從官網(wǎng)上下載 phpStorm 的 Linux 版本: HYPERLINK /phpstorm/download/index.html /phpstorm/download/index.html解壓下載成功的 phpStorm 安裝包: tar xfz PhpStorm-2016.1.tar.gzphpStormbincd phpStorm-2016.1;./phpStorm.sh 在輸入注冊(cè)碼頁(yè)面直接單擊試用版。單擊確定直到出現(xiàn)安裝完成界面。運(yùn)行示例代碼在Windows/Linux/Unix環(huán)境下,請(qǐng)按照以下步驟運(yùn)行示例代碼

41、。 phpStormPHP(工程名無(wú)特殊要求)。將下文具體示例程序中所提供的配置文件(config.ini)以及示例程序(httpProducer.php, httpConsumer.php, Util.php)拷貝到當(dāng)前的工程中,如圖:根據(jù)示例代碼里的說(shuō)明修改相關(guān)配置信息。右鍵點(diǎn)擊創(chuàng)建的 PHP 文件,選擇 Run 執(zhí)行。注意:請(qǐng)先執(zhí)行 httpProducer.php 代碼,再執(zhí)行 httpConsumer.php 代碼。觀察執(zhí)行結(jié)果,如果執(zhí)行結(jié)果有問(wèn)題,請(qǐng)檢查 config.ini 配置是否正確。具體示例程序以下是配置文件(config.ini)、發(fā)送消息(httpProducer.ph

42、p)和接收消息(httpConsumer.php)以及所 用工具方法(Util.php)的示例代碼。配置文件section#您在控制臺(tái)創(chuàng)建的Topic Topic = xxx#公測(cè)環(huán)境的URLsection#您在控制臺(tái)創(chuàng)建的Topic Topic = xxx#公測(cè)環(huán)境的URLURL = HYPERLINK / #阿里云身份驗(yàn)證碼Ak = xxx#阿里云身份驗(yàn)證密鑰Sk = xxx#MQ控制臺(tái)創(chuàng)建的Producer ID ProducerID = xxx#MQ控制臺(tái)創(chuàng)建的Consumer ID ConsumerID = xxxURLKey,TagPOST Content-TypeKeyTag,可

43、以放在 perties 里面。發(fā)送消息示例程序(httpProducer.php)?php/包含工具類(lèi)?php/包含工具類(lèi)include(Util.php);/* 消息發(fā)布者者*/class HttpProducer/簽名private static $signature = Signature;/在MQ控制臺(tái)創(chuàng)建的Producer IDprivate static $producerid = ProducerID;/阿里云身份驗(yàn)證碼private static $aks = AccessKey;/配置信息private static $configs = null;/構(gòu)造函數(shù)function

44、 construct()/讀取配置信息$this:$configs = parse_ini_file(config.ini);/計(jì)算md5private function md5($str)return md5($str);/發(fā)布消息流程public function process()/打印配置信息var_dump($this:$configs);/獲取Topic$topic = $this:$configsTopic;/獲取保存Topic的URL路徑$url = $this:$configsURL;/讀取阿里云訪問(wèn)碼$ak = $this:$configsAk;/讀取阿里云密鑰$sk =

45、$this:$configsSk;/讀取Producer ID$pid = $this:$configsProducerID;/HTTP請(qǐng)求體內(nèi)容$body = utf8_encode(阿里巴巴);$newline = n;/構(gòu)造工具對(duì)象$util = new Util();for ($i = 0; $imd5($body).$newline.$date;/計(jì)算簽名$sign = $util-calSignatue($signString,$sk);/初始化網(wǎng)絡(luò)通信模塊$ch = curl_init();/構(gòu)造簽名標(biāo)記$signFlag = $this:$signature.:.$sign;/

46、構(gòu)造密鑰標(biāo)記$akFlag = $this:$aks.:.$ak;/標(biāo)記$producerFlag = $this:$producerid.:.$pid;/構(gòu)造HTTP請(qǐng)求頭部?jī)?nèi)容類(lèi)型標(biāo)記$contentFlag = Content-Type:text/html;charset=UTF-8;/構(gòu)造HTTP請(qǐng)求頭部$headers = array($signFlag,$akFlag,$producerFlag,$contentFlag,);/設(shè)置HTTP頭部?jī)?nèi)容curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);/ 設(shè) 置 HTTP 請(qǐng) 求 類(lèi) 型 , 此

47、處 為 POST curl_setopt($ch,CURLOPT_CUSTOMREQUEST,POST);/ 設(shè) 置 HTTP 請(qǐng) 求 的 URL curl_setopt($ch,CURLOPT_URL,$postUrl);/ 設(shè) 置 HTTP 請(qǐng) 求 的 body curl_setopt($ch,CURLOPT_POSTFIELDS,$body);/構(gòu)造執(zhí)行環(huán)境ob_start();/開(kāi)始發(fā)送HTTP請(qǐng)求curl_exec($ch);/獲取請(qǐng)求應(yīng)答消息$result = ob_get_contents();/清理執(zhí)行環(huán)境ob_end_clean();/打印請(qǐng)求應(yīng)答結(jié)果var_dump($re

48、sult);/關(guān)閉連接curl_close($ch);/構(gòu)造消息發(fā)布者$producer = new HttpProducer();/啟動(dòng)消息發(fā)布者/啟動(dòng)消息發(fā)布者$producer-process();?接收消息示例程序(httpConsumer.php)通過(guò) HTTP 協(xié)議接收消息,請(qǐng)參考以下示例代碼。calSignatue($signString,$sk);/構(gòu)造簽名標(biāo)記$signFlag = $this:$signature.:.$sign;/構(gòu)造密鑰標(biāo)記$akFlag = $this:$ak.:.$ak;/標(biāo)記$consumerFlag = $this:$consumerid.:.$

49、cid;/構(gòu)造HTTP請(qǐng)求發(fā)送內(nèi)容類(lèi)型標(biāo)記$contentFlag = Content-Type:text/html;charset=UTF-8;/構(gòu)造HTTP頭部信息$headers = array($signFlag,$akFlag,$consumerFlag,$contentFlag,);/構(gòu)造HTTP請(qǐng)求URL$getUrl = $url./message/?topic=.$topic.&time=.$date.&num=32;/初始化網(wǎng)絡(luò)通信模塊$ch = curl_init();/填充HTTP頭部信息curl_setopt($ch,CURLOPT_HTTPHEADER,$heade

50、rs);/ 設(shè) 置 HTTP 請(qǐng) 求 類(lèi) 型 , 此 處 為 GET curl_setopt($ch,CURLOPT_CUSTOMREQUEST,GET);/ 設(shè) 置 HTTP 請(qǐng) 求 URL curl_setopt($ch,CURLOPT_URL,$getUrl);/構(gòu)造執(zhí)行環(huán)境ob_start();/開(kāi)始發(fā)送HTTP請(qǐng)求curl_exec($ch);/獲取請(qǐng)求應(yīng)答消息$result = ob_get_contents();/清理執(zhí)行環(huán)境ob_end_clean();/打印請(qǐng)求應(yīng)答信息var_dump($result);/關(guān)閉HTTP網(wǎng)絡(luò)連接curl_close($ch);/解析HTTP應(yīng)答

51、信息$messages = json_decode($result,true);Topic信息,則直接跳過(guò) if (count($messages=0)continue;/依次遍歷每個(gè)Topic消息foreach (array)$messages as $message)var_dump($message);/獲取時(shí)間戳$date = (int)($util-microtime_float()*1000);/構(gòu)造刪除Topic消息URL$delUrl = $url./message/?msgHandle=.$messagemsgHandle.&topic=.$topic.&time=.$dat

52、e;/簽名字符串$signString = $topic.$newline.$cid.$newline.$messagemsgHandle.$newline.$date;/計(jì)算簽名$sign = $util-calSignatue($signString,$sk);/構(gòu)造簽名標(biāo)記$signFlag = $this:$signature.:.$sign;/構(gòu)造密鑰標(biāo)記$akFlag = $this:$ak.:.$ak;/構(gòu)造消費(fèi)者組標(biāo)記$consumerFlag = $this:$consumerid.:.$cid;/構(gòu)造HTTP請(qǐng)求頭部信息$delheaders = array($signFl

53、ag,$akFlag,$consumerFlag,$contentFlag,);/初始化網(wǎng)絡(luò)通信模塊$ch = curl_init();/填充HTTP請(qǐng)求頭部信息curl_setopt($ch,CURLOPT_HTTPHEADER,$delheaders);/設(shè)置HTTP請(qǐng)求URL信息curl_setopt($ch,CURLOPT_URL,$delUrl);/ 設(shè) 置 HTTP 請(qǐng) 求 類(lèi) 型 , 此 處 為 DELETE curl_setopt($ch,CURLOPT_CUSTOMREQUEST,DELETE);/構(gòu)造執(zhí)行環(huán)境ob_start();/開(kāi)始發(fā)送HTTP請(qǐng)求curl_exec($

54、ch);/開(kāi)始發(fā)送HTTP請(qǐng)求curl_exec($ch);/獲取請(qǐng)求應(yīng)答消息$result = ob_get_contents();/清理執(zhí)行環(huán)境ob_end_clean();/打印應(yīng)答消息var_dump($result);/關(guān)閉連接curl_close($ch);catch (Exception $e)/打印異常信息echo $e-getMessage();/構(gòu)造消息訂閱者$consumer = new HttpConsumer();/啟動(dòng)消息訂閱者$consumer-process();?php/* 工具類(lèi) $blockSize)$key = pack(H*,$hashfunc($ke

55、y);$key = str_pad($key,$blockSize,chr(0 x00);$ipad = str_repeat(chr(0 x36),$blockSize);$opad = str_repeat(chr(0 x5c),$blockSize);$hmac = pack( H*,$hashfunc( ($key$opad).pack(H*,$hashfunc($key$ipad).$str);$sign = base64_encode($hmac);return $sign;/計(jì)算時(shí)間戳public static function microtime_float()list($us

56、ec,$sec) = explode( ,microtime(); return (float)$usec+(float)$sec);?Python 收發(fā)消息本文主要描述如何在 Python 環(huán)境下使用 HTTP 協(xié)議收發(fā) MQ 消息。運(yùn)行環(huán)境準(zhǔn)備用 HTTP 協(xié)議發(fā)送或者接收消息 ,請(qǐng)完成以下環(huán)境準(zhǔn)備工作。WindowsPython( HYPERLINK /downloads/windows/) /downloads/windows/Python2.7。Windows(dospythonPythonLinux/Unix您可以在 Linux 終端輸入 python 指令確認(rèn)是否有預(yù)裝。如果有執(zhí)

57、行信息,則說(shuō)明本臺(tái)機(jī)器已經(jīng)預(yù)裝。如果沒(méi)有,請(qǐng)按以下步驟進(jìn)行安裝:從 Python 官網(wǎng)下載 Python2.7 Linux 版本安裝包: HYPERLINK /download/ /download/在 Python2.7 安裝包下載保存目錄下,運(yùn)行指令進(jìn)行解壓,例如:tar -xzf python-2.7.11.tgz 進(jìn)入2.7.11目錄,執(zhí)行./configure 指令。此步驟主要是用于生成 makefile 文件。執(zhí)行 make 指令進(jìn)行實(shí)際編譯。執(zhí)行 make install 指令進(jìn)行安裝操作。安裝完畢后執(zhí)行 python 命令檢查安裝是否成功,如下圖:運(yùn)行示例代碼按照以下步驟運(yùn)行示

58、例代碼。Windows將下文具體示例程序小節(jié)所提供的配置文件以及示例程序拷貝到本地,并保存為 .py 文件,如下圖:根據(jù)下文示例代碼里的說(shuō)明修改 perties 文件中的相關(guān)字段。將終端窗口切換到保存 .py 的文件目錄,執(zhí)行保存的 python 文件,如下圖:Linux/Unix步驟參見(jiàn) Windows。執(zhí)行結(jié)果參照下圖:具體示例程序您可以參考以下示例程序測(cè)試消息收發(fā)功能。1.配置文件property#您在控制臺(tái)創(chuàng)建的Topic Topic=xxx#公測(cè)集群URLproperty#您在控制臺(tái)創(chuàng)建的Topic Topic=xxx#公測(cè)集群URL HYPERLINK / URL=#阿里云官網(wǎng)身份

59、驗(yàn)證訪問(wèn)碼Ak=xxx#阿里云身份驗(yàn)證密鑰Sk=xxx#MQ控制臺(tái)創(chuàng)建的Producer ID ProducerID=xxx#MQ控制臺(tái)創(chuàng)建的Consumer ID ConsumerID=xxx說(shuō)明:URL中的 Key,Tag 以及 POST Content-Type 沒(méi)有任何的限制,只要確保 Key 和 Tag 相同唯一即可,可以放在 perties 里面。2.發(fā)送消息示例程序通過(guò) HTTP 協(xié)議發(fā)送消息,請(qǐng)參考以下示例代碼。#encoding:utf-8 import ConfigParser import hashlib import httplib import timefrom ur

60、lparse import urlparsefrom Util import parseURL,calSignature消息發(fā)布者class HttpProducer(object):def init (self): 簽名值self.signature = SignatureProducerID ducerid = ProducerID 消 息 主 題 self.topic = Topic訪問(wèn)碼self.ak = AccessKey配置文件解析器self.cf = ConfigParser.ConfigParser()MD5對(duì)象self.md5 = hashlib.md5()發(fā)布消息主流程de

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶(hù)所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶(hù)上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶(hù)上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶(hù)因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論