阿里云消息队列MQ_HTTP接入 for .NetCore 简单例子
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; namespace MQWebCore
{
public class MQHelper
{
string URL = "http://publictest-rest.ons.aliyun.com"; string topic, secretKey, accessKey;
public MQHelper(string topic,string secretKey,string accessKey)
{
this.topic = topic;
this.secretKey = secretKey;
this.accessKey = accessKey; }
/// <summary>
/// URL 中的 Key,Tag以及 POST Content-Type 没有任何的限制,只要确保Key 和 Tag 相同唯一即可
/// </summary>
/// <param name="tag"></param>
/// <param name="key"></param>
/// <param name="body"></param>
/// <returns></returns>
public async Task<bool> Pub(string tag, string key, string body)
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Connection.Add("keep-alive");
HttpContent content = new StringContent(body, Encoding.UTF8);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
var time = (long)(DateTime.Now.ToUniversalTime() - new DateTime(, , )).TotalMilliseconds;
var signString = Sign(string.Format("{0}\nPID_{0}\n{1}\n{2}", topic, MD5Encrypt(body), time), secretKey); httpClient.DefaultRequestHeaders.Add("AccessKey", accessKey);
httpClient.DefaultRequestHeaders.Add("Signature", signString);
httpClient.DefaultRequestHeaders.Add("ProducerID", string.Format("PID_{0}", topic)); var url = URL + "/message/?topic=" + topic + "&time=" + time + "&tag=" + tag + "&key=" + key;
var res = await httpClient.PostAsync(url, content);
if (res.StatusCode == System.Net.HttpStatusCode.Created)
{
return true;
}
return false;
}
} public async void Subscribe(string tag = "*")
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Connection.Add("keep-alive");
httpClient.DefaultRequestHeaders.Add("Accept-Charset", "utf-8");
var time = (long)(DateTime.Now.ToUniversalTime() - new DateTime(, , )).TotalMilliseconds;
var signString = Sign(string.Format("{0}\nCID_{0}\n{1}", topic, time), secretKey); httpClient.DefaultRequestHeaders.Add("AccessKey", accessKey);
httpClient.DefaultRequestHeaders.Add("Signature", signString);
httpClient.DefaultRequestHeaders.Add("ConsumerID", string.Format("CID_{0}", topic)); var url = URL + "/message/?topic=" + topic + "&time=" + time + "&num=32";
var res = httpClient.GetAsync(url).GetAwaiter().GetResult();
Console.WriteLine(res.StatusCode);
if (res.StatusCode == System.Net.HttpStatusCode.OK)
{
var msg = await res.Content.ReadAsStringAsync();
Console.WriteLine(msg);
if (msg != null && msg.Length > )
{
MQMessage[] mqMsgs = JsonConvert.DeserializeObject<MQMessage[]>(msg);
foreach (var mqMsg in mqMsgs)
{
Delete(mqMsg.msgHandle);
}
}
}
}
} async void Delete(string msgHandle)
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
var time = (long)(DateTime.Now.ToUniversalTime() - new DateTime(, , )).TotalMilliseconds;
var signString = Sign(string.Format("{0}\nCID_{0}\n{1}\n{2}", topic, msgHandle, time), secretKey); httpClient.DefaultRequestHeaders.Add("AccessKey", accessKey);
httpClient.DefaultRequestHeaders.Add("Signature", signString);
httpClient.DefaultRequestHeaders.Add("ConsumerID", string.Format("CID_{0}", topic)); var url = URL + "/message/?topic=" + topic + "&time=" + time + "&msgHandle=" + msgHandle;
var res = await httpClient.DeleteAsync(url);
if (res.StatusCode == System.Net.HttpStatusCode.NoContent)
{
Console.WriteLine("消息删除成功,无需返回内容");
}
else
{
Console.WriteLine(res.StatusCode);
}
}
} string MD5Encrypt(string strText)
{
using (var md5 = MD5.Create())
{
var result = md5.ComputeHash(Encoding.UTF8.GetBytes(strText));
return BitConverter.ToString(result).Replace("-", "").ToLower();
}
} string Sign(string signatureString, string secretKey, bool isRaw = true)
{
var enc = Encoding.UTF8;
HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(secretKey));
hmac.Initialize(); byte[] buffer = enc.GetBytes(signatureString);
if (isRaw)
{
byte[] ret = hmac.ComputeHash(buffer);
return Convert.ToBase64String(ret);
}
else
{
string res = BitConverter.ToString(hmac.ComputeHash(buffer)).Replace("-", "").ToLower();
return Convert.ToBase64String(Encoding.UTF8.GetBytes(res));
}
}
} public class MQMessage
{
public string body;
public string bornTime;
public string msgHandle;
public string msgId;
public long reconsumeTimes;
public string tag;
}
using MQWebCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace ConsoleApp1
{
public class Program
{
public static void Main(string[] args)
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
//Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
MQHelper mqHelper = new MQHelper("Test", "3412qsd's12", "3412341212");
var res = mqHelper.Pub("testTag", "testKey", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "阿特斯地方").GetAwaiter().GetResult();
Debug.WriteLine(res);
while (true)
{
mqHelper.Subscribe();
Thread.Sleep();
}
Console.Read(); }
}
}
阿里云消息队列MQ_HTTP接入 for .NetCore 简单例子的更多相关文章
- 使用java实现阿里云消息队列简单封装
一.前言 最近公司有使用阿里云消息队列的需求,为了更加方便使用,本人用了几天时间将消息队列封装成api调用方式以方便内部系统的调用,现在已经完成,特此记录其中过程和使用到的相关技术,与君共勉. 现在阿 ...
- Sping Boot入门到实战之实战篇(一):实现自定义Spring Boot Starter——阿里云消息队列服务Starter
在 Sping Boot入门到实战之入门篇(四):Spring Boot自动化配置 这篇中,我们知道Spring Boot自动化配置的实现,主要由如下几部分完成: @EnableAutoConfigu ...
- 阿里云 消息队列mq
使用阿里云消息队列 控制台地址:http://ons.console.aliyun.com/#/home/topic Demo: 支付消息mq工厂类: public class DfacePayCon ...
- 阿里云消息队列(MQ)服务
A.首先在阿里云上申请消息队列MQ服务: B.然后创建一个Topic(主题,一级主题):然后创建生产者与消费者: C.不过此时还没有结束 ,还需要创建一个AccessKey和AccessSecret( ...
- 阿里云消息队列的C#使用http接口发送消息实例
app.config <appSettings> <clear/> <add key="Ons_Topic" value="XXX_Fini ...
- 阿里云视频直播PHP-SDK接入教程
阿里云视频直播PHP-SDK接入教程 阿里云 视频直播 配置 及 PHP-SDK 接入教程 准备工作 域名管理 配置鉴权 地址生成器及DEMO演 ...
- C#阿里云 移动推送 接入
接入阿里云的 移动推送 SDK,实现在后台直接 发送消息给APP的功能. ----------------OpenAPI进行推送 2.0高级接口 阿里云配置准备:1.移动app配置:打开 ...
- 微软云消息队列 Azure service bus queue
前言 第一次使用消息队列,遇到了一些问题:同一个消息有多次出列.是一个消息只入列一次,还是多次?还是因为出列问题,出列了多次? Microsoft Azure service bus queue Az ...
- php与阿里云短信接口接入
使用阿里云短信API,需要在控制台获取以下必要参数,其中需要自己手机验证+官方审核多次,尤其审核需要保持耐心. 1. accessKeyId 相当于你的个人账户密钥: 2. accessKeySec ...
随机推荐
- 让结构体类型frame的某个属性可以直接修改
本篇是是本人在博客园写的第一篇博客,前几天因为种种原因最终决定离开混了几年的csdn.希望在博客园有个新的开始 Foundation框架里面的frame是大家最熟悉不过的一个属性了,但是修改起来比较麻 ...
- linux 系统权限 数字含义
摘抄: sudo chmod XXX dir_name XXX是你要设置的权限代号,第一位代表Owner,第二位代表Group,第三位代表Others XXX中0代表什么都不可以,1代表可执行,2代表 ...
- CEF3可行性
Chromium Embedded Framework 顾名思义,内嵌式CHROME,详细的介绍参阅 http://yogurtcat.com/posts/cef/hello-cef.html 为什么 ...
- php文件下载
public function down() { $lang = strtolower(cookie('think_language')); if ($lang == 'en-us') { $file ...
- 学习 HTML5-目录
1.学习 HTML5-页面结构 2.HTML5标记 3.HTML5机构化语义元素 4.HTML5表单 5.HTML5媒体元素:Audio和Video 6.HTML5绘图API 7.HTML5 Canv ...
- 1.2 《硬啃设计模式》 第2章 学习设计模式需掌握的UML知识
要看懂设计模式,你需要懂类图(Class Diagram),也需要懂一点对象图(Object Diagram),下面介绍一些UML的必要知识,以便你学习设计模式. 属性.操作 下图简单介绍类的属性和操 ...
- Spring为某个属性注入值或为某个方法的返回值
项目中用到需要初始化一些数据,Spring提供了filed的值注入和method的返回值注入. 一.Field值的注入 filed值注入需要使用org.springframework.beans.fa ...
- VS2015 Git 插件使用教程
VS2015 中继承了 Git 插件,再也不用下载 Github for Windows了. 从 团队-管理连接 中打开 团队资源管理器 克隆Repository 在 本地 Git 存储库下面点击 ...
- Tomcat:使用JMX监管Tomcat的几种方式
Tomcat使用JMX管理方式,在Tomcat的自带应用manager就是使用了JMX方式来管理Tomcat,以此完成Web应用的动态部署.启动.停止. 然而manager应用是一种本地使用JMX接口 ...
- centos安装php php-fpm
centos安装php php-fpm 1.下载php源码包 http://www.php.net/downloads.php 2 .安装php tar -xvf php-5.5.13.tar.bz2 ...