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 简单例子的更多相关文章

  1. 使用java实现阿里云消息队列简单封装

    一.前言 最近公司有使用阿里云消息队列的需求,为了更加方便使用,本人用了几天时间将消息队列封装成api调用方式以方便内部系统的调用,现在已经完成,特此记录其中过程和使用到的相关技术,与君共勉. 现在阿 ...

  2. Sping Boot入门到实战之实战篇(一):实现自定义Spring Boot Starter——阿里云消息队列服务Starter

    在 Sping Boot入门到实战之入门篇(四):Spring Boot自动化配置 这篇中,我们知道Spring Boot自动化配置的实现,主要由如下几部分完成: @EnableAutoConfigu ...

  3. 阿里云 消息队列mq

    使用阿里云消息队列 控制台地址:http://ons.console.aliyun.com/#/home/topic Demo: 支付消息mq工厂类: public class DfacePayCon ...

  4. 阿里云消息队列(MQ)服务

    A.首先在阿里云上申请消息队列MQ服务: B.然后创建一个Topic(主题,一级主题):然后创建生产者与消费者: C.不过此时还没有结束 ,还需要创建一个AccessKey和AccessSecret( ...

  5. 阿里云消息队列的C#使用http接口发送消息实例

    app.config <appSettings> <clear/> <add key="Ons_Topic" value="XXX_Fini ...

  6. 阿里云视频直播PHP-SDK接入教程

    阿里云视频直播PHP-SDK接入教程 阿里云 视频直播 配置 及 PHP-SDK 接入教程        准备工作        域名管理        配置鉴权        地址生成器及DEMO演 ...

  7. C#阿里云 移动推送 接入

    接入阿里云的 移动推送 SDK,实现在后台直接 发送消息给APP的功能.        ----------------OpenAPI进行推送 2.0高级接口 阿里云配置准备:1.移动app配置:打开 ...

  8. 微软云消息队列 Azure service bus queue

    前言 第一次使用消息队列,遇到了一些问题:同一个消息有多次出列.是一个消息只入列一次,还是多次?还是因为出列问题,出列了多次? Microsoft Azure service bus queue Az ...

  9. php与阿里云短信接口接入

    使用阿里云短信API,需要在控制台获取以下必要参数,其中需要自己手机验证+官方审核多次,尤其审核需要保持耐心. 1. accessKeyId  相当于你的个人账户密钥: 2. accessKeySec ...

随机推荐

  1. 自定义JSP标签库及Properties使用

    自定义JSP标签库及Properties使用 自定义JSP标签 自定义JSP标签技术是在JSP 1.1版本中才出现的,它支持用户在JSP文件中自定义标签,这样可以使JSP代码更加简洁. 这些可重用的标 ...

  2. Android studio git 本地仓库和远程仓库节点对比

    1.初始状态 2.本地修改文件,然后commit 3.本地再次修改文件,然后commit 4.本地push 从上图可以看出,push完成后,本地仓库的节点和远程仓库的节点是一样的.

  3. Swift tour

    输出函数: print(“hello world!") 无需引入函数库,无须使用“;”作为语句结尾,也无须写跟其它语言一样的main()函数,Swift中,全局区的代码就是程序入口.You ...

  4. HTTPS学习总结

    p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 21.0px Verdana; color: #393939 } span.s1 { } HTTPS学习总结 ...

  5. 编译生成IOS开发使用的FFmpeg的过程

    前言:本篇随笔纯属是参照<iOS 使用 FFmpeg>的过程,本人自己操作了一遍,但是本人记性不好,觉得这样的过程可以记录在博客中,以后需要可以快速回头翻阅细节.所以特地参考<iOS ...

  6. google不能访问的根本解决方法

    最近中国的防火墙又调皮了.直接出现404了.以前通过IP访问的方式也失效了.难道这种问题能难倒我们这些做技术的IT工程师么?! 经过我的查询,我发现还是有大神在研究这块的.大神针对开发经常访问的网站做 ...

  7. IntelliJ IDEA 使用总结[zz]

    本文转自:http://cowboy-bebop.iteye.com/blog/1035550,仅做稍微整理,转载请注明出处. 1. IDEA内存优化 因机器本身的配置而配置: \IntelliJ I ...

  8. DbUtils是Apache出品一款简化JDBC开发的工具类

    DbUtils     - DbUtils是Apache出品一款简化JDBC开发的工具类     - 使用DbUtils可以让我们JDBC的开发更加简单     - DbUtils的使用:       ...

  9. 关于SQLSERVER2012版本远程登录问题

    最近公司新配置了一台服务器,安装的数据库版本为sqlserver2012企业版本,一切安装正常,本地登录也正常 需要远程客户端登录,防火墙也开放的端口,路由器也做了端口映射,因为我们有两台服务器,14 ...

  10. jQuery 更改checkbox的状态,无效

    今天写页面遇到复选框动态全选或全不选问题,正常写法如下: $("#tb").find("input[type='checkbox']").attr(" ...