消息队列、OSS常用操作封装
- public class MessageQueue
- {
- #region Private Properties
- private const string _accessKeyId = "";
- private const string _secretAccessKey = "";
- private const string _endpoint = "";
- private static string _queueName;
- private const int _receiveTimes = 1;
- private const int _receiveInterval = 2;
- private const int batchSize = 6;
- #endregion
- #region 设置队列名称
- public string queueName
- {
- set
- {
- _queueName = value;
- }
- get
- {
- return _queueName;
- }
- }
- #endregion
- #region 判断消息队列是否存在
- /// <summary>
- /// 判断消息队列是否存在
- /// </summary>
- /// <returns></returns>
- public static bool QueueIsExist()
- {
- bool flag = false;
- try
- {
- using (IMNS client = new Aliyun.MNS.MNSClient(_accessKeyId, _secretAccessKey, _endpoint))
- {
- var nativeQueue = client.GetNativeQueue(_queueName);
- var getQueueAttributesResponse = nativeQueue.GetAttributes();
- flag = true;
- }
- }
- catch (Exception ex) { Console.WriteLine(ex.ToString()); }
- return flag;
- }
- #endregion
- #region 创建消息队列
- /// <summary>
- /// 创建消息队列
- /// </summary>
- /// <returns></returns>
- public static string CreateQueue()
- {
- /*
- DelaySeconds 发送到该 Queue 的所有消息默认将以DelaySeconds参数指定的秒数延后可被消费,单位为秒。 0-604800秒(7天)范围内某个整数值,默认值为0
- MaximumMessageSize 发送到该Queue的消息体的最大长度,单位为byte。 1024(1KB)-65536(64KB)范围内的某个整数值,默认值为65536(64KB)。
- MessageRetentionPeriod 消息在该 Queue 中最长的存活时间,从发送到该队列开始经过此参数指定的时间后,不论消息是否被取出过都将被删除,单位为秒。 60 (1分钟)-1296000 (15 天)范围内某个整数值,默认值345600 (4 天)
- VisibilityTimeout 消息从该 Queue 中取出后从Active状态变成Inactive状态后的持续时间,单位为秒。 1-43200(12小时)范围内的某个值整数值,默认为30(秒)
- PollingWaitSeconds 当 Queue 中没有消息时,针对该 Queue 的 ReceiveMessage 请求最长的等待时间,单位为秒。 0-30秒范围内的某个整数值,默认为0(秒)
- LoggingEnabled 是否开启日志管理功能,True表示启用,False表示停用 True/False,默认为False
- */
- string queueName = string.Empty;
- var createQueueRequest = new CreateQueueRequest
- {
- QueueName = _queueName,
- Attributes =
- {
- DelaySeconds = 0,
- MaximumMessageSize = 65536,
- MessageRetentionPeriod = 345600,
- VisibilityTimeout = 3600,
- PollingWaitSeconds = 3
- }
- };
- try
- {
- using (IMNS client = new Aliyun.MNS.MNSClient(_accessKeyId, _secretAccessKey, _endpoint))
- {
- var queue = client.CreateQueue(createQueueRequest);
- queueName = queue.QueueName;
- }
- }
- catch (Exception ex) { Console.WriteLine(ex.ToString()); }
- Thread.Sleep(2000);
- return queueName;
- }
- #endregion
- #region 删除消息队列
- /// <summary>
- /// 删除消息队列
- /// </summary>
- /// <returns></returns>
- public static bool DeleteQueue()
- {
- bool flag = false;
- var deleteQueueRequest = new DeleteQueueRequest(_queueName);
- deleteQueueRequest.AddHeader("Accept", "IE6"); //Add extra request headers
- //deleteQueueRequest.AddParameter("param1", "value1"); //InvalidQueryString
- try
- {
- using (IMNS client = new Aliyun.MNS.MNSClient(_accessKeyId, _secretAccessKey, _endpoint))
- {
- var deleteQueueResponse = client.DeleteQueue(deleteQueueRequest);
- flag = true;
- }
- }
- catch (Exception ex) { Console.WriteLine(ex.ToString()); }
- return flag;
- }
- #endregion
- #region 发送消息(单条或多条)
- /// <summary>
- /// 发送消息(单条或多条)
- /// </summary>
- /// <param name="models">SendMessageRequest集合</param>
- /// <returns></returns>
- public static bool BathSendMessage(List<SendMessageRequest> models)
- {
- bool flag = false;
- try
- {
- using (IMNS client = new Aliyun.MNS.MNSClient(_accessKeyId, _secretAccessKey, _endpoint))
- {
- var nativeQueue = client.GetNativeQueue(_queueName);
- List<SendMessageRequest> requests = new List<SendMessageRequest>();
- for (int i = 0; i < models.Count; i++)
- {
- requests.Add(models[i]);
- }
- BatchSendMessageRequest batchSendRequest = new BatchSendMessageRequest()
- {
- Requests = requests
- };
- var sendMessageResponse = nativeQueue.BatchSendMessage(batchSendRequest);
- flag = true;
- }
- }
- catch (Exception ex) { Console.WriteLine(ex.ToString()); }
- return flag;
- }
- #endregion
- #region 消费消息(单条或多条)
- /// <summary>
- /// 消费消息(单条或多条)
- /// </summary>
- /// <param name="itemNum">数目</param>
- /// <returns></returns>
- public static List<Message> ReceiveMessage(int itemNum)
- {
- List<Message> lists = new List<Message>();
- try
- {
- using (IMNS client = new Aliyun.MNS.MNSClient(_accessKeyId, _secretAccessKey, _endpoint))
- {
- var nativeQueue = client.GetNativeQueue(_queueName);
- for (int i = 0; i < itemNum; i++)
- {
- var receiveMessageResponse = nativeQueue.ReceiveMessage();
- Message message = receiveMessageResponse.Message;
- lists.Add(message);
- }
- }
- }
- catch (Exception ex) { Console.WriteLine(ex.ToString()); }
- return lists;
- }
- #endregion
- #region 删除消息
- /// <summary>
- /// 删除消息
- /// </summary>
- /// <param name="receiptHandle">receiptHandle</param>
- /// <returns></returns>
- public static bool DeleteMessage(string receiptHandle)
- {
- bool flag = false;
- var deletedReceiptHandle = receiptHandle;
- try
- {
- using (IMNS client = new Aliyun.MNS.MNSClient(_accessKeyId, _secretAccessKey, _endpoint))
- {
- var nativeQueue = client.GetNativeQueue(_queueName);
- var deleteMessageResponse = nativeQueue.DeleteMessage(receiptHandle);
- flag = true;
- }
- }
- catch (Exception ex) { Console.WriteLine(ex.ToString()); }
- return flag;
- }
- #endregion
- #region 修改消息可见时间
- /// <summary>
- /// 修改消息可见时间
- /// </summary>
- /// <param name="receiptHandle">receiptHandle</param>
- /// <param name="visibilityTimeout">从现在到下次可被用来消费的时间间隔</param>
- /// <returns></returns>
- public static bool ChangeMessageVisibility(string receiptHandle, int visibilityTimeout)
- {
- bool flag = false;
- var deletedReceiptHandle = receiptHandle;
- try
- {
- using (IMNS client = new Aliyun.MNS.MNSClient(_accessKeyId, _secretAccessKey, _endpoint))
- {
- var nativeQueue = client.GetNativeQueue(_queueName);
- var changeMessageVisibilityRequest = new ChangeMessageVisibilityRequest
- {
- ReceiptHandle = receiptHandle,
- VisibilityTimeout = visibilityTimeout
- };
- var changeMessageVisibilityResponse = nativeQueue.ChangeMessageVisibility(changeMessageVisibilityRequest);
- flag = true;
- }
- }
- catch (Exception ex) { Console.WriteLine(ex.ToString()); }
- return flag;
- }
- #endregion
- }
- using System;
- using System.IO;
- using System.Text;
- using System.Threading;
- using System.Security.Cryptography;
- using Aliyun.OSS.Common;
- namespace Aliyun.OSS.Samples
- {
- /// <summary>
- /// 获取OSS对象
- /// </summary>
- public static class GetObjectSample
- {
- static string accessKeyId = Config.AccessKeyId;
- static string accessKeySecret = Config.AccessKeySecret;
- static string endpoint = Config.Endpoint;
- static OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);
- static string key = "123456.jpg";
- static string fileToUpload = Config.FileToUpload;
- static string dirToDownload = Config.DirToDownload;
- static AutoResetEvent _event = new AutoResetEvent(false);
- public static void GetObjects(string bucketName)
- {
- GetObject(bucketName); //获取文件
- GetObjectByRequest(bucketName);
- AsyncGetObject(bucketName); //异步方式获取文件
- }
- public static void GetObject(string bucketName)
- {
- try
- {
- client.PutObject(bucketName, key, fileToUpload);
- var result = client.GetObject(bucketName, key);
- using (var requestStream = result.Content)
- {
- using (var fs = File.Open(Path.Combine(dirToDownload, key), FileMode.OpenOrCreate))
- {
- int length = 4 * 1024;
- var buf = new byte[length];
- do
- {
- length = requestStream.Read(buf, 0, length);
- fs.Write(buf, 0, length);
- } while (length != 0);
- }
- }
- Console.WriteLine("Get object succeeded");
- }
- catch (OssException ex)
- {
- Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
- ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
- }
- catch (Exception ex)
- {
- Console.WriteLine("Failed with error info: {0}", ex.Message);
- }
- }
- public static void GetObjectByRequest(string bucketName)
- {
- try
- {
- client.PutObject(bucketName, key, fileToUpload);
- var request = new GetObjectRequest(bucketName, key);
- request.SetRange(0, 100);
- var result = client.GetObject(request);
- Console.WriteLine("Get object succeeded, length:{0}", result.Metadata.ContentLength);
- }
- catch (OssException ex)
- {
- Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
- ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
- }
- catch (Exception ex)
- {
- Console.WriteLine("Failed with error info: {0}", ex.Message);
- }
- }
- public static void AsyncGetObject(string bucketName)
- {
- const string key = "AsyncGetObject";
- try
- {
- client.PutObject(bucketName, key, fileToUpload);
- string result = "Notice user: put object finish";
- client.BeginGetObject(bucketName, key, GetObjectCallback, result.Clone());
- _event.WaitOne();
- }
- catch (OssException ex)
- {
- Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
- ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
- }
- catch (Exception ex)
- {
- Console.WriteLine("Failed with error info: {0}", ex.Message);
- }
- }
- private static void GetObjectCallback(IAsyncResult ar)
- {
- try
- {
- var result = client.EndGetObject(ar);
- using (var requestStream = result.Content)
- {
- using (var fs = File.Open(dirToDownload + "/sample2.data", FileMode.OpenOrCreate))
- {
- int length = 4 * 1024;
- var buf = new byte[length];
- do
- {
- length = requestStream.Read(buf, 0, length);
- fs.Write(buf, 0, length);
- } while (length != 0);
- }
- }
- Console.WriteLine(ar.AsyncState as string);
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- finally
- {
- _event.Set();
- }
- }
- }
- }
- using System;
- using System.Collections.Generic;
- using Aliyun.OSS.Common;
- namespace Aliyun.OSS.Samples
- {
- /// <summary>
- /// 删除OSS对象
- /// </summary>
- public static class DeleteObjectsSample
- {
- static string accessKeyId = Config.AccessKeyId;
- static string accessKeySecret = Config.AccessKeySecret;
- static string endpoint = Config.Endpoint;
- static OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);
- public static void DeleteObject(string bucketName)
- {
- try
- {
- string key = null;
- var listResult = client.ListObjects(bucketName);
- foreach (var summary in listResult.ObjectSummaries)
- {
- key = summary.Key;
- break;
- }
- client.DeleteObject(bucketName, key);
- Console.WriteLine("Delete object succeeded");
- }
- catch (OssException ex)
- {
- Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
- ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
- }
- catch (Exception ex)
- {
- Console.WriteLine("Failed with error info: {0}", ex.Message);
- }
- }
- public static void DeleteObjects(string bucketName)
- {
- try
- {
- var keys = new List<string>();
- var listResult = client.ListObjects(bucketName);
- foreach (var summary in listResult.ObjectSummaries)
- {
- keys.Add(summary.Key);
- break; //不跳出删除全部
- }
- var request = new DeleteObjectsRequest(bucketName, keys, false);
- client.DeleteObjects(request);
- Console.WriteLine("Delete objects succeeded");
- }
- catch (OssException ex)
- {
- Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
- ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
- }
- catch (Exception ex)
- {
- Console.WriteLine("Failed with error info: {0}", ex.Message);
- }
- }
- }
- }
- using System;
- using System.IO;
- using System.Threading;
- using Aliyun.OSS.Common;
- using System.Text;
- using Aliyun.OSS.Util;
- namespace Aliyun.OSS.Samples
- {
- /// <summary>
- /// 上传文件或对象到OSS
- /// </summary>
- public static class PutObjectSample
- {
- static string accessKeyId = Config.AccessKeyId;
- static string accessKeySecret = Config.AccessKeySecret;
- static string endpoint = Config.Endpoint;
- static OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);
- static string fileToUpload = Config.FileToUpload;
- static AutoResetEvent _event = new AutoResetEvent(false);
- /// <summary>
- /// sample for put object to oss
- /// </summary>
- public static void PutObject(string bucketName)
- {
- PutObjectFromFile(bucketName); //上传文件
- PutObjectFromString(bucketName); //上传String
- PutObjectWithDir(bucketName); //创建目录上传
- PutObjectWithMd5(bucketName); //MD5验证上传
- PutObjectWithHeader(bucketName); //设置Header上传
- AsyncPutObject(bucketName); //异步上传
- }
- public static void PutObjectFromFile(string bucketName)
- {
- const string key = "PutObjectFromFile";
- try
- {
- client.PutObject(bucketName, key, fileToUpload);
- Console.WriteLine("Put object:{0} succeeded", key);
- }
- catch (OssException ex)
- {
- Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
- ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
- }
- catch (Exception ex)
- {
- Console.WriteLine("Failed with error info: {0}", ex.Message);
- }
- }
- public static void PutObjectFromString(string bucketName)
- {
- const string key = "PutObjectFromString";
- const string str = "Aliyun OSS SDK for C#";
- try
- {
- byte[] binaryData = Encoding.ASCII.GetBytes(str);
- var stream = new MemoryStream(binaryData);
- client.PutObject(bucketName, key, stream);
- Console.WriteLine("Put object:{0} succeeded", key);
- }
- catch (OssException ex)
- {
- Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
- ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
- }
- catch (Exception ex)
- {
- Console.WriteLine("Failed with error info: {0}", ex.Message);
- }
- }
- public static void PutObjectWithDir(string bucketName)
- {
- const string key = "folder/sub_folder/PutObjectFromFile";
- try
- {
- client.PutObject(bucketName, key, fileToUpload);
- Console.WriteLine("Put object:{0} succeeded", key);
- }
- catch (OssException ex)
- {
- Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
- ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
- }
- catch (Exception ex)
- {
- Console.WriteLine("Failed with error info: {0}", ex.Message);
- }
- }
- public static void PutObjectWithMd5(string bucketName)
- {
- const string key = "PutObjectWithMd5";
- string md5;
- using (var fs = File.Open(fileToUpload, FileMode.Open))
- {
- md5 = OssUtils.ComputeContentMd5(fs, fs.Length);
- }
- var meta = new ObjectMetadata() { ContentMd5 = md5 };
- try
- {
- client.PutObject(bucketName, key, fileToUpload, meta);
- Console.WriteLine("Put object:{0} succeeded", key);
- }
- catch (OssException ex)
- {
- Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
- ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
- }
- catch (Exception ex)
- {
- Console.WriteLine("Failed with error info: {0}", ex.Message);
- }
- }
- public static void PutObjectWithHeader(string bucketName)
- {
- const string key = "PutObjectWithHeader";
- try
- {
- using (var content = File.Open(fileToUpload, FileMode.Open))
- {
- var metadata = new ObjectMetadata();
- metadata.ContentLength = content.Length;
- metadata.UserMetadata.Add("github-account", "qiyuewuyi");
- client.PutObject(bucketName, key, content, metadata);
- Console.WriteLine("Put object:{0} succeeded", key);
- }
- }
- catch (OssException ex)
- {
- Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
- ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
- }
- catch (Exception ex)
- {
- Console.WriteLine("Failed with error info: {0}", ex.Message);
- }
- }
- public static void AsyncPutObject(string bucketName)
- {
- const string key = "AsyncPutObject";
- try
- {
- // 1. put object to specified output stream
- using (var fs = File.Open(fileToUpload, FileMode.Open))
- {
- var metadata = new ObjectMetadata();
- metadata.UserMetadata.Add("mykey1", "myval1");
- metadata.UserMetadata.Add("mykey2", "myval2");
- metadata.CacheControl = "No-Cache";
- metadata.ContentType = "text/html";
- string result = "Notice user: put object finish";
- client.BeginPutObject(bucketName, key, fs, metadata, PutObjectCallback, result.ToCharArray());
- _event.WaitOne();
- }
- }
- catch (OssException ex)
- {
- Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
- ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
- }
- catch (Exception ex)
- {
- Console.WriteLine("Failed with error info: {0}", ex.Message);
- }
- }
- private static void PutObjectCallback(IAsyncResult ar)
- {
- try
- {
- client.EndPutObject(ar);
- Console.WriteLine(ar.AsyncState as string);
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- finally
- {
- _event.Set();
- }
- }
- }
- }
消息队列、OSS常用操作封装的更多相关文章
- .Net Excel操作之NPOI(二)常用操作封装
一.Excel数据导出常用操作 1.指定表头和描述 2.指定数据库中读出的数据集合 二.ExcelExport封装 /// <summary> /// Excel常用的表格导出逻辑封装 / ...
- python openpyxl 2.5.4 版本 excel常用操作封装
最近搭框架用的openpyxl 2.5.4版本,之前封装的函数有些提示不推荐使用了,我做了一些更新: 代码: # encoding=utf-8 from openpyxl import load_wo ...
- linux消息队列操作
对消息队列的操作无非有以下三种类型: 1. 打开或创建消息队列消息队列的内核持续性要求每一个消息队列都在系统范围内相应唯一的键值,所以,要获得一个消息队列的描写叙述字,仅仅需提供该消息队列的键值就可以 ...
- Python操作rabbitmq消息队列持久化
消息队列持久化 Python操作rabbit消息队列的持久化,如下: # 创建一个名为balance的队列,对queue进行durable持久化设为True(持久化第一步)channel.queue_ ...
- MSMQ消息队列 用法
引言 接下来的三篇文章是讨论有关企业分布式开发的文章,这三篇文章筹划了很长时间,文章的技术并不算新,但是文章中使用到的技术都是经过笔者研究实践后总结的,正所谓站在巨人的肩膀上,笔者并不是巨人,但也希望 ...
- 跟我一起学WCF(1)——MSMQ消息队列
一.引言 Windows Communication Foundation(WCF)是Microsoft为构建面向服务的应用程序而提供的统一编程模型,该服务模型提供了支持松散耦合和版本管理的序列化功能 ...
- Linux环境进程间通信(三):消息队列
linux下进程间通信的几种主要手段: 管道(Pipe)及有名管道(named pipe):管道可用于具有亲缘关系进程间的通信,有名管道克服了管道没有名字的限制,因此,除具有管道所具有的功能外,它还允 ...
- 消息队列 概念 配合SpringBoot使用Demo
转http://www.jianshu.com/p/048e954dab40 概念: 分布式消息队列 ‘分布式消息队列’包含两个概念 一是‘消息队列’,二是‘分布式’ 那么就先看下消息队列的概念,和为 ...
- WCF之MSMQ消息队列
一.MSMQ简介 MSMQ(微软消息队列)是Windows操作系统中消息应用程序的基础,是用于创建分布式.松散连接的消息通讯应用程序的开发工具. MSMQ与XML Web Services和.Net ...
随机推荐
- centos 7 && dotnet core 2.0 && nginx && supervisor
前提 系统:centos 7 目录:/home/wwwroot/www.wuball.com dotnet core 2.0 官方指引 sudo rpm --import https://packag ...
- 201521123073 《Java程序设计》第1周学习总结
1.本章学习总结 你对于本章知识的学习总结 1.Java中使用Scanner处理输入,需要注意如下几个地方 程序开头必须import java.util.Scanner导入Scanner类. 使用Sc ...
- Android事件机制
一句话描述: 用户和程序之间的互动机制 什么是事件? 用户和程序交互时触发的程序操作. 只要是事件,必须具备三方面: 1 事件的发生者 2 事件接受者 3 事件触发和传递 事件处理的方法 观察者模式: ...
- 201521123009 《Java程序设计》第10周学习总结
1. 本周学习总结 2. 书面作业 本次PTA作业题集异常.多线程 Q1:finally 题目4-2 1.1 截图你的提交结果(出现学号) 1.2 4-2中finally中捕获异常需要注意什么? tr ...
- Java课程设计-计算器
1.团队课程设计博客链接 http://www.cnblogs.com/yuanj/p/7072137.html 2.个人负责模块或任务说明 监听器的设置 3.自己的代码提交记录截图 //注册各个组件 ...
- 201521123012 《Java程序设计》第十三周学习总结
1. 本周学习总结 1.1 以你喜欢的方式(思维导图.OneNote或其他)归纳总结多网络相关内容. 2. 书面作业 1. 网络基础 1.1 比较ping www.baidu.com与ping cec ...
- 201521123089 《Java程序设计》第12周学习总结
1. 本周学习总结 1. Input Stream -- 数据提供者可从其中读数据输出流:Output Stream -- 数据接收者可往其中写数据: 2. 字符流底层具体读写操作还是使用字节流: 3 ...
- AIX盘rw_timeout值过小导致IO ERROR
刚下班没多久,接收到告警提示数据库的数据文件异常,且同时收到主机硬盘的IO ERROR告警 该数据库服务器为AIX+oracle 9i环境,登录主机验证关键日志告警 发现确实在18点48分有磁盘IO的 ...
- AJAX多级下拉联动【JSON】
前言 前面我们已经使用过了XML作为数据载体在AJAX中与服务器进行交互.当时候我们的案例是二级联动,使用Servlet进行控制 这次我们使用JSON作为数据载体在AJAX与服务器交互,使用三级联动, ...
- Spring - lookup-method方式实现依赖注入
引言 假设一个单例模式的bean A需要引用另外一个非单例模式的bean B,为了在我们每次引用的时候都能拿到最新的bean B,我们可以让bean A通过实现ApplicationContextWa ...