之前都是在博客园看别人的文章,今天开始就开启自己的博客咯,欢迎阅读,共同探讨!
简单点说Widows Azure Storage就是一个大的网盘,可以让用户存储任何想存储的数据,数据一旦存储到“云”中就永远不会丢失,程序员可以在任何时候,任何终端,任何地点获取任意大小的数据。
目前来说,Windoows Azure Storage 是由4部分组成,如下:
1.Windows Azure Blob Service:主要存储一些大型的Unstructure的数据,Text or Binary,像Media, Document等等。
2.Windows Azure Table Service:以前在开发一些Asp.net程序的时候,大多数会使用关系型数据库(SQL Server),往往一个应用程序中的类对应数据库中的某些表,然后你需要大量的代码或者工具来完成关系数据库到对象之间的映射,这个时候你是多么想直接将实体类存储到数据库当中呀!Windows Azure Table服务就是来解决这个问题的。它可以直接将实体类、实体对象存入到表结构当中,它和一般的关系型数据库中的Table很像,当时也有很大的不同,比如它不能提供像SQL中的Join方法,也不能管理Foreign Key.
3.Windows Azure Queue Service:不同于前两种都是在存储或者读取数据,Queue Service主要是用来存储消息队列,应用得最多的就是为Work Role和Web Role来传递消息。
4.Windows Azure File Storage:提供在云上的文件共享服务,你可以存储任何你需要共享的文件,比如用得比较多的就是共享应用程序的配置文件,日志文件,Crash Dumps等等。同样也可以实现在多台虚拟机上挂载共享存储。
下面分别介绍下这4种存储的结构,如下:
1.Blob Storage Concepts:
Storage Account:所有对Storage的操作都是通过Storage Account来完成的,可以说是Azure Storage的入口.
Container:Container提供了一组Blob的分组,一个Accout能包含无个数限制的Container,一个Container能包含无个数限制的Blo.
Blob:任何类型或者大小的文件。在这里用得比较多的是Block Blob.它是存储text或者Binary的理想选择。Page Blob其实和Black Blob很像,因为它就是Black Blob组成的。比较适用于存储逐渐增长的这种数据,Like Logging.还有一种就是Page Block,对于那种需要频繁的读写操作的存储更加高效,一般作为虚拟机的Data Disk比较多。
2.Table Storage Concepts:
Storage Account:所有对Storage的操作都是通过Storage Account来完成的,可以说是Azure Storage的入口.
Table:存储实体类或者实体对象(Entity)的集合.
Entity:一组属性的实体,类似于数据库的行.
Properties:一个属性就是一个Name-Value的键值对,每个实体(Entity)有3个系统的属性, partition key, a row key, and a timestamp.
3.Queue Storage Concepts
Storage Account:所有对Storage的操作都是通过Storage Account来完成的,可以说是Azure Storage的入口.
Queue:存储message.
4.File Storage Concepts
Storage Account:所有对Storage的操作都是通过Storage Account来完成的,可以说是Azure Storage的入口.
Share:是Azure上的一个File Share的地方,所有的Directory或者File都必须在share里面创建.
Directory:可选的在这种层级里面.
File:需要共享的文件.
最后介绍下这4种结构的创建和一些常见的用法,如下:
这4种存储都可以通过Azure Portal或者Power Shell来创建和操作,具体可以参考:https://azure.microsoft.com/en-us/documentation/articles/storage-introduction/
下面我们介绍以编程的方式分别访问这几种Storage:
1.Blob:

1 public class BlobStorage 2 { 3 public CloudStorageAccount storageAccount; 4 public CloudBlobClient blobClient; 5 public CloudBlobContainer container; 6 7 public void initial() 8 { 9 //CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString); 10 storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=mystoraget;AccountKey=mykey"); 11 12 blobClient = storageAccount.CreateCloudBlobClient(); 13 container = blobClient.GetContainerReference("mycontainer"); 14 container.CreateIfNotExists(); 15 } 16 17 //Upload a file into a container 18 public void UploadBlodToContainer() 19 { 20 container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob }); 21 22 CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob"); 23 using (var filestream = System.IO.File.OpenRead(@"C:data.txt")) 24 { 25 blockBlob.UploadFromStream(filestream); 26 } 27 CloudBlockBlob blockBlob2 = container.GetBlockBlobReference("myblob2"); 28 using (var filestream = System.IO.File.OpenRead(@"C:MyFoldermytext.txt")) 29 { 30 blockBlob2.UploadFromStream(filestream); 31 } 32 33 Console.WriteLine("Upload blob to container succeed!"); 34 } 35 36 //List the blobs in a container 37 public void ListBlodFromContainer() 38 { 39 foreach (IListBlobItem item in container.ListBlobs(null, false)) 40 { 41 if (item.GetType() == typeof(CloudBlockBlob)) 42 { 43 CloudBlockBlob blob = (CloudBlockBlob)item; 44 Console.WriteLine("Block blob of length {0}: {1}", blob.Properties.Length, blob.Uri); 45 } 46 else if (item.GetType() == typeof(CloudPageBlob)) 47 { 48 CloudPageBlob pageBlob = (CloudPageBlob)item; 49 50 Console.WriteLine("Page blob of length {0}: {1}", pageBlob.Properties.Length, pageBlob.Uri); 51 } 52 53 } 54 Console.WriteLine("List Blod succeed!"); 55 } 56 57 //Download file from blobs 58 public void DownloadToStream() 59 { 60 CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob"); 61 62 using (var fileStream = System.IO.File.OpenWrite(@"C:MyFolderInputext.txt")) 63 { 64 blockBlob.DownloadToStream(fileStream); 65 } 66 67 Console.WriteLine("Download blob to stream succeed!"); 68 } 69 70 //Delete blob 71 public void DeleteBlob() 72 { 73 CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob"); 74 75 blockBlob.Delete(); 76 Console.WriteLine("Delete blob succeed!"); 77 } 78 }
2.Table

1 public class TableStorage 2 { 3 public CloudStorageAccount storageAccount; 4 public CloudTableClient tableClient; 5 public CloudTable table; 6 7 //Create a table 8 public void initial() 9 { 10 storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=mystoraget;AccountKey=mykey"); 11 12 tableClient = storageAccount.CreateCloudTableClient(); 13 table = tableClient.GetTableReference("people"); 14 table.CreateIfNotExists(); 15 } 16 17 //Add an entity to a table 18 public void AddEntityToTable() 19 { 20 CustomerEntity customer1 = new CustomerEntity("Harp", "Walter"); 21 customer1.Email = "Walter@contoso.com"; 22 customer1.PhoneNumber = "425-555-0101"; 23 TableOperation inserOperation = TableOperation.Insert(customer1); 24 25 table.Execute(inserOperation); 26 Console.WriteLine("Insert entity to a table succeed"); 27 } 28 29 //Insert a batch of entities 30 public void AddbatchEntityToTable() 31 { 32 TableBatchOperation batchOperation = new TableBatchOperation(); 33 34 CustomerEntity customer1 = new CustomerEntity("Smith", "Jeff"); 35 customer1.Email = "Jeff@contoso.com"; 36 customer1.PhoneNumber = "425-555-0104"; 37 38 CustomerEntity customer2 = new CustomerEntity("Smith", "Ben"); 39 customer2.Email = "Ben@contoso.com"; 40 customer1.PhoneNumber = "425-555-0102"; 41 42 batchOperation.Insert(customer1); 43 batchOperation.Insert(customer2); 44 45 table.ExecuteBatch(batchOperation); 46 Console.WriteLine("Insert a batch of entities to a table succeed"); 47 } 48 49 //Query a table for all Entity 50 public void QueryEntityFromTable() 51 { 52 TableQuery<CustomerEntity> query = new TableQuery<CustomerEntity>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "Smith")); 53 foreach (CustomerEntity entity in table.ExecuteQuery(query)) 54 { 55 Console.WriteLine("{0}, {1} {2} {3}", entity.PartitionKey, entity.RowKey, 56 entity.Email, entity.PhoneNumber); 57 } 58 } 59 60 //Delete Entity from table 61 public void DeleteEntityFromTable() 62 { 63 TableOperation retrieveOperation = TableOperation.Retrieve<CustomerEntity>("Smith", "Ben"); 64 TableResult retrievedResult = table.Execute(retrieveOperation); 65 66 CustomerEntity deleteEntity = (CustomerEntity)retrievedResult.Result; 67 if (deleteEntity != null) 68 { 69 TableOperation deleteOperation = TableOperation.Delete(deleteEntity); 70 71 // Execute the operation. 72 table.Execute(deleteOperation); 73 74 Console.WriteLine("Entity deleted."); 75 } 76 77 else 78 Console.WriteLine("Could not retrieve the entity."); 79 } 80 81 //delete a table 82 public void deletetable() 83 { 84 table.DeleteIfExists(); 85 Console.WriteLine("Delete table successful!"); 86 } 87 }
3.Queue

1 public class QueueStorage 2 { 3 public CloudStorageAccount storageAccount; 4 public CloudQueueClient queueClient; 5 public CloudQueue queue; 6 7 public void initial() 8 { 9 storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=mystoraget;AccountKey=mykey"); 10 11 queueClient = storageAccount.CreateCloudQueueClient(); 12 queue = queueClient.GetQueueReference("myqueue"); 13 queue.CreateIfNotExists(); 14 } 15 16 //Inser a message into a queue 17 public void InsertMessageToQueue() 18 { 19 CloudQueueMessage message = new CloudQueueMessage("Hello,World"); 20 CloudQueueMessage message2 = new CloudQueueMessage("Hello2,World2"); 21 queue.AddMessage(message2); 22 queue.AddMessage(message); 23 Console.WriteLine("Insert Message to queue succeed!"); 24 } 25 26 27 //get message 28 public void GetMessage() 29 { 30 CloudQueueMessage retrieveMessage = queue.GetMessage(); 31 Console.WriteLine("Retrieved message with content'{0}'", retrieveMessage.AsString); 32 } 33 34 35 //update the content of a queued message 36 public void UpdateMessage() 37 { 38 CloudQueueMessage message = queue.GetMessage(); 39 Console.WriteLine("Retrieved message with content'{0}'", message.AsString); 40 message.SetMessageContent("Updated."); 41 queue.UpdateMessage(message, TimeSpan.FromSeconds(10.0), MessageUpdateFields.Content | MessageUpdateFields.Visibility); 42 Console.WriteLine("Update Message complete, I will appear after 10s"); 43 } 44 45 //test async 46 public async Task AsyncPattern() 47 { 48 if (await queue.CreateIfNotExistsAsync()) 49 { 50 Console.WriteLine("Queue '{0}' Created", queue.Name); 51 } 52 else 53 { 54 Console.WriteLine("Queue '{0}' Exists", queue.Name); 55 } 56 57 CloudQueueMessage cloudQueueMessage = new CloudQueueMessage("My message"); 58 59 await queue.AddMessageAsync(cloudQueueMessage); 60 Console.WriteLine("Message added"); 61 62 CloudQueueMessage retrievedMessage = await queue.GetMessageAsync(); 63 Console.WriteLine("Retrieved message with content'{0}'", retrievedMessage.AsString); 64 65 await queue.DeleteMessageAsync(retrievedMessage); 66 Console.WriteLine("Deleted message"); 67 68 69 } 70 }
4.File

1 public class FileStorage 2 { 3 public CloudStorageAccount storageAccount; 4 public CloudFileClient fileClient; 5 public CloudFileShare share; 6 public CloudFileDirectory rootDir; 7 public CloudFileDirectory sampleDir; 8 9 //Create a table 10 public void initial() 11 { 12 storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=mystoraget;AccountKey=mykey"); 13 14 fileClient = storageAccount.CreateCloudFileClient(); 15 share = fileClient.GetShareReference("testfiledemo"); 16 share.CreateIfNotExists(); 17 18 rootDir = share.GetRootDirectoryReference(); 19 sampleDir = rootDir.GetDirectoryReference("Images"); 20 sampleDir.CreateIfNotExists(); 21 } 22 23 //upload file to directory in file share 24 public void UploadFile() 25 { 26 CloudFile sourceFile = sampleDir.GetFileReference("sample-file.txt"); 27 sourceFile.Create(2); 28 using (var filestream = System.IO.File.OpenRead(@"C:aa.txt")) 29 { 30 sourceFile.UploadFromStream(filestream); 31 } 32 Console.WriteLine("Upload file to directory succeed!"); 33 } 34 //Download the file 35 public void DownloadFile() 36 { 37 CloudFile file = sampleDir.GetFileReference("sample-file.txt"); 38 Console.WriteLine(file.DownloadTextAsync().Result); 39 } 40 41 42 //Copy file to a blob 43 public void CopyFileToBlob() 44 { 45 CloudFileShare share = fileClient.GetShareReference("sample-share"); 46 share.CreateIfNotExists(); 47 48 49 CloudFile sourceFile = share.GetRootDirectoryReference().GetFileReference("sample-file.txt"); 50 51 sourceFile.UploadText("A sample file in the root directory."); 52 53 CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); 54 CloudBlobContainer container = blobClient.GetContainerReference("sample-container"); 55 container.CreateIfNotExists(); 56 CloudBlockBlob desBlob = container.GetBlockBlobReference("sample-container"); 57 58 string fileSas = sourceFile.GetSharedAccessSignature(new SharedAccessFilePolicy() 59 { 60 Permissions =SharedAccessFilePermissions.Read, 61 SharedAccessExpiryTime=DateTime.UtcNow.AddHours(24) 62 }); 63 64 Uri fileSasUri = new Uri(sourceFile.StorageUri.PrimaryUri.ToString()+fileSas); 65 66 desBlob.StartCopy(fileSasUri); 67 68 Console.WriteLine("source file contents:{0}", sourceFile.DownloadText()); 69 Console.WriteLine("destination blob contents:{0}",desBlob.DownloadText()); 70 } 71 72 //delete file share 73 public void DeleteFileShare() 74 { 75 share.Delete(); 76 77 Console.WriteLine("Delete file share success!"); 78 } 79 } 80 }