阿里云消息队列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 ...
随机推荐
- SQL for SQLite
语法 verb + subject + predicate commannds(命令) SQL由命令组成,以分号为结束.命令有token组成,token由white space分隔,包括空格.tab. ...
- NSValue&NSNumber
void testForNSValue(void) { int i=10; // NSLog(@"encode(int)=%s",@encode(int)); // N ...
- iOS 开发之路(登陆页键盘遮挡输入框问题)一
在学习开发登陆页的时候,遇到的问题分享如下: 首先是swift 3.0 中,NotificationCenter 设置 selector 如下: @IBOutlet weak var bottomCo ...
- 我的android学习经历7
android签名后报错的问题 Duplicate id @+id/imageView, already defined earlier in this layout,android生成报错 这个是项 ...
- iOS block从零开始
iOS block从零开始 在iOS4.0之后,block横空出世,它本身封装了一段代码并将这段代码当做变量,通过block()的方式进行回调. block的结构 先来一段简单的代码看看: void ...
- NPOI对Excel的操作(Sheet转DataTable、List<T>)
通过NPOI对Excel进行操作,这里主要是读取的操作.封装到ExcelHelper操作类中. 1 using System.Collections.Generic; 2 using NPOI.HSS ...
- 【转发】NPAPI学习(Firefox和Chrome扩展开发 )
NPAPI学习(Firefox和Chrome扩展开发 ) 2011-11-08 14:41:02 by [6yang], 1172 visits, 收藏 | 返回 Firefox和Chrome扩展开发 ...
- ORACLE关于索引是否需要定期重建争论的整理
ORACLE数据库中的索引到底要不要定期重建呢? 如果不需要定期重建,那么理由是什么? 如果需要定期重建,那么理由又是什么?另外,如果需要定期重建,那么满足那些条件的索引才需要重建呢?关于这个问题,网 ...
- SQL挑战——如何高效生成编码
有这样一个需求:需要根据输入的编码(这个编码值来自于数据库的一个表)生成下一个编码,编码规则如下所示(我们暂且不关心这个逻辑是否合理,只关心如何实现): 1: 最小值为A0000, 最大值为ZZZZZ ...
- [Linux监控]磁盘空间大小
echo 192.168.10.69>>ip.list ------------------------------------------- #!/bin/bash #注意if和[]之间 ...