博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
第一个Azure应用
阅读量:4552 次
发布时间:2019-06-08

本文共 8118 字,大约阅读时间需要 27 分钟。

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
Get([FromBody]string value) { Dictionary
item = new Dictionary
(); 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 = 12;            // 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(5)); if (msg != null) { Dictionary
item = msg.GetBody
>(); 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(0, 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
{ "Subnet-1" } }; #endregion #region 5. Role List
Configurations = new List
(); 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
() { vmRole }); VirtualMachineCreateDeploymentParameters createDeploymentParams = new VirtualMachineCreateDeploymentParameters { Name = "deploymentName", Label = "serviceName", Roles = new List
() { 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);        }}

 

转载于:https://www.cnblogs.com/Betty-IT/p/9274340.html

你可能感兴趣的文章
NEFU 109
查看>>
HDU 5435
查看>>
thinkphp的目录结构设计经验总结
查看>>
9月23日
查看>>
java 括号匹配 成对
查看>>
三级联动下拉列表——php 、Ajax
查看>>
取自ACE中的bit操作宏(转)
查看>>
git从已有分支拉新分支开发
查看>>
滚动条隐藏兼容写法
查看>>
SQL2005查询所有表的大小
查看>>
Shell 正则表达式
查看>>
Docker run命令参数整理
查看>>
create-react-app简单操作
查看>>
2016年5月29日晚上(传智Bootstrap笔记五(表单2))
查看>>
IAR嵌入式工作台IDE _ (__no_init)
查看>>
【转】高斯投影及其中央子午线的判断
查看>>
Access提示Insert Into 语法错误解决办法总结
查看>>
Spark之 SparkSql、DataFrame、DataSet介绍
查看>>
Linux Shell基础 - Bash变量 - 环境变量 - 位置参数变量 - 预定义变量
查看>>
java.lang.NoClassDefFoundError: org/apache/commons/lang/StringUtils...
查看>>