如何在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 资源 。
#您在控制台创建的Topic
Topic=xxx
#公测url
URL=http://publictest-rest.ons.aliyun.com
#阿里云身份验证码
Ak=xxx
#阿里云身份验证密钥
Sk=xxx
#MQ控制台创建的Producer ID
ProducerID=xxx
#MQ控制台创建的Consumer ID
ConsumerID=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配置您的Topic
String url=properties.getProperty("URL");//公测集群配置为http://publictest-rest.ons.aliyun.com/
String ak=properties.getProperty("Ak");//请在user.properties配置您的Ak
String sk=properties.getProperty("Sk");//请在user.properties配置您的Sk
String pid=properties.getProperty("ProducerID");//请在user.properties配置您的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 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配置您的topic
String url=properties.getProperty("URL");//公测集群配置为http://publictest-rest.ons.aliyun.com/
String ak=properties.getProperty("Ak");//请在user.properties配置您的Ak
String sk=properties.getProperty("Sk");//请在user.properties配置您的Sk
String cid=properties.getProperty("ConsumerID");//请在user.properties配置您的Consumer ID
String 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;
}
}
如何在Java 环境下使用 HTTP 协议收发 MQ 消息的更多相关文章
- 4.1. 如何在Windows环境下开发Python
4.1. 如何在Windows环境下开发Python 4.1. 如何在Windows环境下开发Python 4.1.1. Python的最原始的开发方式是什么样的 4.1.1.1. 找个文本编辑器,新 ...
- 《安卓网络编程》之第一篇 java环境下模拟客户端、服务器端
1.Socket简介 在网络上的两个程序通过一个双向的通信连接实现数据的交换,这个双向链路的一端称为一个Socket.Socket通常用来实现客户方和服务方的连接.Socket是TCP/IP协议的一个 ...
- NLPIR分词工具的使用(java环境下)
一.NLPIR是什么? NLPIR(汉语分词系统)由中科大张华平博士团队开发,主要功能包括:中文分词,词性标注,命名实体识别,用户词典功能,详情见官网:http://ictclas.nlpir.org ...
- Java 环境下使用 AES 加密的特殊问题处理
在 Java 环境下使用 AES 加密,在密钥长度和字节填充方面有一些比较特殊的处理. 1. 密钥长度问题 默认 Java 中仅支持 128 位密钥,当使用 256 位密钥的时候,会报告密钥长度错误 ...
- 有了SSL证书,如何在IIS环境下部署https?【转载】
昨天各位小伙伴都很开心的领取了自己的SSL证书,但是大部分小伙伴却不知道如何部署,也许是因为第一次接触SSL这种高端的东西吧,不过个人觉得就是懒懒懒...本来小编也挺懒的,但是答应了各位小伙伴的,那么 ...
- Java环境下shiro的测试-认证与授权
Java环境下shiro的测试 1.导入依赖的核心jar包 <dependency> <groupId>org.apache.shiro</groupId> < ...
- 如何在Windows环境下安装Linux系统虚拟机
如何在Windows环境下安装Linux系统虚拟机 本篇经验写给想要入门学习C语言的小白们.Windows系统因为使用窗口图形化,操作简单,功能多样,所以我们在Windows环境下可以做到很多,但想要 ...
- 这是关于FastJson的一个使用Demo,在Java环境下验证的
public class User { private int id; private String name; public int getId() { return id; } public vo ...
- 有了SSL证书,如何在IIS环境下部署https?
昨天各位小伙伴都很开心的领取了自己的SSL证书,但是大部分小伙伴却不知道如何部署,也许是因为第一次接触SSL这种高端的东西吧,不过个人觉得就是懒懒懒...本来小编也挺懒的,但是答应了各位小伙伴的,那么 ...
随机推荐
- Android Bitmap 缩放 旋转 水印 裁剪操作
在android当中,Bitmap代表一个图片,里面封装了图片相关的信息. 一.将图片进行缩放操作 1.获得Bitmap对象 Bitmap bitmap = BitmapFactory.decodeR ...
- 使用PD进行数据库建模时的问题
在PowerDesigner中建立好概念模型后,将其转为物理模型的时候出现如下错误提示: 前面四个是相同的问题,原因是由于没有修改默认设置.可以在Tools--->Model Options-& ...
- MVC教程七:扩展HtmlHelper方法
在上一篇文章的最后,列出了一些常见的HtmlHelper的方法,这些都是ASP.NET MVC已经定义好的,如果我们想自己定义一个HtmlHelper方法可以吗?答案是肯定的,那么如何自定义一个Htm ...
- Qt入门——使用QT+VS2008开发windows应用程序
1.文件->新建->项目 Qt4 Projects 右边已安装模板当中选择At Application. 确定 2.选择需要使用的QT库 下一步 3. “class name”:指定类的名 ...
- CentOS 7系统LAMP配置PHP-FPM的示例
CentOS 7 系统出来有一段时间了,今天我们来看在vps中的 CentOS 7 中给lamp环境配置php-fpm的过程,希望文章可以帮助到各位. CentOS 7 已经发布,并且采用 Apach ...
- org.apache.catalina.LifecycleException异常的处理
今天调试了很久,重装tomcat都没用,后来发现是xml servlet的url-pattern的配置少写一个"/",添加后启动即可. org.apache.catalina.Li ...
- Linux 内核版本,Ubuntu版本的查看
查看内核版本 1) cat /proc/version [root@a ~]# cat /proc/version Linux version 2.6.18-194.el5 (mockbuild@x ...
- python3 异步模块asyncio
yield方法引入, 这里存在的问题是,如果你想创建从0到1,000,000这样一个很大的序列,你不得不创建能容纳1,000,000个整数的列表. 但是当加入了生成器之后,你可以不用创建完整的序列,你 ...
- (笔记)Linux下的静态库和动态库使用详解
库从本质上来说是一种可执行代码的二进制格式,可以被载入内存中执行.库分静态库和动态库两种. 一.静态库和动态库的区别 1. 静态函数库 这类库的名字一般是libxxx.a:利用静态函数库编译成的文件比 ...
- AFNetWorking能做什么
AFNetwork是一个轻量级的网络请求api类库.是以NSURLConnection, NSOperation和其它方法为基础的. 以下这个样例是用来处理json请求的: NSURL *url = ...