https://www.azure.cn/zh-cn/

学习Azure,首先看的是官网Azure介绍,因为用到了虚拟机及存储等因此,着重看这两块。

本文Demo是通过API发送消息,当收到消息后新建虚拟机并启动虚拟机。

详细步骤:

1.新建Azure Cloud应用程序,添加WebRole以及WorkerRole,WebRole对应的是WebAPI

2.具体代码

WebRole中实现发送消息

public class AzureMessageController : ApiController
{
// POST api/AzureMessage
[HttpGet]
[Route ("api/AzureMessage")]
public Dictionary<string, string> Get([FromBody]string value)
{
Dictionary<string, string> item = new Dictionary<string, string>();
item.Add("name", "Jerry");
QueueClient client = QueueClient.Create("queue", ReceiveMode.ReceiveAndDelete);
BrokeredMessage msg = new BrokeredMessage(item);
try
{
client.Send(msg);
}
catch
{
throw;
}
finally
{
client.Close();
}
return item;
}
}

WorkerRole中在WorkerRole.cs中实现接收消息并新建虚拟机,开启虚拟机,及Stop动作

 private static QueueClient client;
private IComputeManagementClient csClient;
private INetworkManagementClient netClient;

a. OnStart()中开启消息队列客户端

public override bool OnStart()
{
// Set the maximum number of concurrent connections
ServicePointManager.DefaultConnectionLimit = ; // For information on handling configuration changes
// see the MSDN topic at https://go.microsoft.com/fwlink/?LinkId=166357. client = QueueClient.Create("queue", ReceiveMode.ReceiveAndDelete);
Trace.TraceInformation("MyWorkerRole has been started"); return base.OnStart();
}

b. OnStop()中关闭消息队列客户端

public override void OnStop()
{
Trace.TraceInformation("MyWorkerRole is stopping"); //this.cancellationTokenSource.Cancel();
//this.runCompleteEvent.WaitOne();
client.Close();
base.OnStop(); Trace.TraceInformation("MyWorkerRole has stopped");
}

c. Run()接收消息后,对虚拟机操作

 public override  void Run()
{
Trace.TraceInformation("MyWorkerRole is running");
//while (true)
//{
BrokeredMessage msg = client.Receive(TimeSpan.FromSeconds());
if (msg != null)
{
Dictionary<string, string> item = msg.GetBody<Dictionary<string,string>>();
Trace.TraceInformation("Messages received name: "+item["name"]);
//Create VM
#region 1. create certificattion to client
X509Certificate2 certificate = null;
string thumbprint = "这里是证书所需要的thumbprint";
certificate = new X509Certificate2(Convert.FromBase64String(thumbprint));
Microsoft.Azure.SubscriptionCloudCredentials CloudCredential = new Microsoft.Azure.CertificateCloudCredentials("这里是云服务证书序列", certificate);
csClient = new ComputeManagementClient(CloudCredential);
#endregion
#region 2. create cloudservice---serviceName
var list = csClient.HostedServices.List();
csClient.HostedServices.BeginDeletingAll("serviceName");
var hostServicesPar = new Microsoft.WindowsAzure.Management.Compute.Models.HostedServiceCreateParameters("serviceName", "label")
{
Location = "West US"
}; csClient.HostedServices.Create(hostServicesPar); #endregion
#region 3. osVHD
OSVirtualHardDisk osVHD = null;
//osVHD = csClient.VirtualMachineOSImages.CreateOSVHD(_parameters.CloudServiceName, _parameters.NodeName, _parameters.Image);
var res = csClient.VirtualMachineOSImages.Get("imageName"); //提前定制好的Image
Uri ur = res.MediaLinkUri;
string UrlPath = ur.AbsoluteUri;
string Result = UrlPath.Substring(, UrlPath.LastIndexOf('/')); osVHD = new OSVirtualHardDisk
{
MediaLink = VMClass.GetVhdUri(Result,"serviceName", "vmName"),
SourceImageName = "imageName",
};
#endregion
#region 4. vnet
netClient = new NetworkManagementClient(CloudCredential);
var netlist = netClient.Networks.List();
ConfigurationSet conset = new ConfigurationSet
{
ConfigurationSetType = ConfigurationSetTypes.NetworkConfiguration,
SubnetNames = new List<string> { "Subnet-1" }
}; #endregion
#region 5. Role List <ConfigurationSet> Configurations = new List<ConfigurationSet>();
Configurations.Add(conset); Configurations.Add(new ConfigurationSet
{
AdminUserName = "userName",
AdminPassword = "userPWD",
ConfigurationSetType = ConfigurationSetTypes.WindowsProvisioningConfiguration,
EnableAutomaticUpdates = true,
ResetPasswordOnFirstLogon = false,
ComputerName = "MyComputerName", });
//}
Microsoft.WindowsAzure.Management.Compute.Models.Role vmRole = new Microsoft.WindowsAzure.Management.Compute.Models.Role
{
RoleType = VirtualMachineRoleType.PersistentVMRole.ToString(),
RoleName = "MyRoleName",
Label = "label",
RoleSize = "Standard_DS1_v2",
// VMImageName = imageName,
OSVirtualHardDisk = osVHD,
ProvisionGuestAgent = true,
ConfigurationSets = Configurations
};
#endregion
#region 6. check demployment
//check demployment
DeploymentGetResponse demployment = null;
try
{
demployment = csClient.Deployments.GetBySlot("serviceName", DeploymentSlot.Production);
}
catch { } if (demployment != null)
{
//csClient.VirtualMachines.CreateVM(_parameters.HostSvcName, _parameters.HostSvcName, vmRole);
VirtualMachineCreateParameters parameters = new VirtualMachineCreateParameters()
{
ConfigurationSets = vmRole.ConfigurationSets,
ProvisionGuestAgent = true,
RoleName = vmRole.RoleName,
RoleSize = vmRole.RoleSize,
OSVirtualHardDisk = vmRole.OSVirtualHardDisk,
//VMImageName = vmRole.VMImageName,
ResourceExtensionReferences = vmRole.ResourceExtensionReferences, };
if (parameters.OSVirtualHardDisk == null)
{
parameters.VMImageName = vmRole.VMImageName;
};
csClient.VirtualMachines.Create("serviceName", "deploymentName", parameters);
}
else
{
//csClient.VirtualMachines.CreateVMDeployment(_parameters.HostSvcName, _parameters.HostSvcName, _parameters.VirtualNetworkName, new List<Role>() { vmRole });
VirtualMachineCreateDeploymentParameters createDeploymentParams = new VirtualMachineCreateDeploymentParameters
{
Name = "deploymentName",
Label = "serviceName",
Roles = new List<Microsoft.WindowsAzure.Management.Compute.Models.Role>() { vmRole },
DeploymentSlot = DeploymentSlot.Production,
VirtualNetworkName = "WDSOQASubCVnet01"
};
Trace.TraceInformation("Begin creating VM: " + item["name"]);
csClient.VirtualMachines.CreateDeployment("serviceName", createDeploymentParams);
Trace.TraceInformation("End : " + item["name"]);
Trace.TraceInformation("VM information : " );
Trace.TraceInformation("VM information Cloudservice: xx");
Trace.TraceInformation("VM information Name: xx");
Trace.TraceInformation("VM information VNet: WDSOQASubCVnet01");
Trace.TraceInformation("VM information Size: Standard_DS1_v2");
}
#endregion
}
}

用到的自定义的类

public static class VMClass
{
public static Uri GetVhdUri(string blobcontainerAddress, string cloudServiceName, string vmName,
bool cacheDisk = false, bool https = false)
{
var now = DateTime.UtcNow;
string dateString = now.Year + "-" + now.Month + "-" + now.Day;
string timeString = now.Hour + "-" + now.Second;
var address = string.Format("{0}/{1}-{2}-{3}-{4}-650.vhd", blobcontainerAddress, cloudServiceName, vmName, cacheDisk ? "-CacheDisk" : timeString, dateString);
return new Uri(address);
}
}

第一个Azure应用的更多相关文章

  1. ASP.NET Core 中文文档 第二章 指南(3)用 Visual Studio 发布一个 Azure 云 Web 应用程序

    原文:Getting Started 作者:Rick Anderson 翻译:谢炀(Kiler) 校对:孟帅洋(书缘).刘怡(AlexLEWIS).何镇汐 设置开发环境 安装最新版本的 Azure S ...

  2. 初码-Azure系列-存储队列的使用与一个Azure小工具(蓝天助手)

    初码Azure系列文章目录 将消息队列技术模型简化,并打造成更适合互联网+与敏捷开发的云服务模式,好像已经是行业趋势,阿里云也在推荐使用消息服务(HTTP协议为主)而来替代消息队列(TCP协议.MQT ...

  3. 一个Azure VM RDP连接问题

    由于Azure上的VM都是通过同一个镜像文件创建的,有时会需要修改SID. 在给一台VM修改SID重启后,就无法通过RDP连接到虚机了,从Azure管理界面的启动诊断界面上可以看到虚拟停在一个要求用户 ...

  4. 落地Azure CosmosDb的一个项目分享

    我们遇到了什么? 我们有这么一个业务场景,就是某供应商会去爬取某些数据,爬到后会发到一个FTP上,然后我们定时去获取这些数据 这个数据有大有小,小的30多M数据量百万级,大的数据量能到数百M上千万数据 ...

  5. Azure Queue Storage 基本用法 -- Azure Storage 之 Queue

    Azure Storage 是微软 Azure 云提供的云端存储解决方案,当前支持的存储类型有 Blob.Queue.File 和 Table. 笔者在<Azure File Storage 基 ...

  6. Azure File Storage 基本用法 -- Azure Storage 之 File

    Azure Storage 是微软 Azure 云提供的云端存储解决方案,当前支持的存储类型有 Blob.Queue.File 和 Table. 笔者在<Azure Blob Storage 基 ...

  7. Azure机器学习入门(二)创建Azure机器学习工作区

    我们将开始深入了解如何使用Azure机器学习的基本功能,帮助您开始迈向Azure机器学习的数据科学家之路. Azure ML Studio (Azure Machine Learning Studio ...

  8. 迁移 SQL Server 数据库到 Azure SQL 实战

    最近有个维护的项目需要把 SQL Server 2012 的数据库迁移到 Azure SQL 上去,迁移过程可谓一波三折,故在此分享这次迁移中碰到的点点滴滴,希望对朋友们有所帮助. 文章来源:葡萄城产 ...

  9. Azure的负载均衡机制

    负载均衡一直是一个比较重要的议题,几乎所有的Azure案例或者场景都不可避免,鉴于经常有客户会问,所以笔者觉得有必要总结一下. Azure提供的负载均衡机制,按照功能,可以分为三种:Azure Loa ...

随机推荐

  1. springboot使用@data注解,减少不必要代码

    一.idea安装lombok插件 二.重启idea 三.添加maven依赖 <dependency> <groupId>org.projectlombok</groupI ...

  2. oracle 事务 与 提交

    Oracle事务 一般事务(DML)即数据修改(增.删.改)的事务事务会将所有在事务中被修改的数据行加上锁(行级锁),来阻止其它人(会话)同时对这些数据的修改操作.当事务被提交或回滚后,这些数据才会被 ...

  3. Charles 抓包工具(新猿旺学习总结)

    Charles 抓包工具安装机操作 1.Charles 抓包工具是代理服务器工具,可以拦截数据,进行更改,返回数据,以实现前端后台的请求和响应数据的测试2.Charles 菜单介绍 Charles抓包 ...

  4. 【shell】awk按域去除重复行

    首先解释一下什么叫“按域去除重复行”: 有的时候我们需要去除的重复行并不是整行都重复,两行的其中一列的元素相同我们有的时候就需要认定这两行重复,因此有了今天的内容. 去除重复行shell有一个原生命令 ...

  5. Bugku-CTF之成绩单(快来查查成绩吧)

    Day18 成绩单 快来查查成绩吧http://123.206.87.240:8002/chengjidan/ 本题要点:sql手注.查询基础命令 首先查看一下源码  

  6. Django Form表单组件

    Form介绍 我们之前在HTML页面中利用form表单向后端提交数据时,都会写一些获取用户输入的标签并且用form标签把它们包起来. 与此同时我们在好多场景下都需要对用户的输入做校验,比如校验用户是否 ...

  7. Python内置进制转换函数(实现16进制和ASCII转换)

    在进行wireshark抓包时你会发现底端窗口报文内容左边是十六进制数字,右边是每两个十六进制转换的ASCII字符,这里使用Python代码实现一个十六进制和ASCII的转换方法. hex() 转换一 ...

  8. 阿里云ECS相关

    RAM授权: https://help.aliyun.com/document_detail/28639.html 安全组: https://jingyan.baidu.com/article/afd ...

  9. mui中confirm在苹果出现bug,confirm点击确定跳转页面再返回后,页面被遮罩盖住无法使用

    项目中使用confirm mui.confirm('您还未抽奖,现在去抽奖吗?', function (res) { if (res.index === 1) { window.location.hr ...

  10. Qt对象树

    Qt提供了一种机制,能够自动.有效的组织和管理继承自QObject的Qt对象,这种机制就是对象树.子对象动态分配空间不需要释放.