https://www.azure.cn/zh-cn/api
學習Azure,首先看的是官網Azure介紹,由於用到了虛擬機及存儲等所以,着重看這兩塊。ide
本文Demo是經過API發送消息,當收到消息後新建虛擬機並啓動虛擬機。學習
詳細步驟:this
1.新建Azure Cloud應用程序,添加WebRole以及WorkerRole,WebRole對應的是WebAPIspa
2.具體代碼code
WebRole中實現發送消息orm
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動做blog
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()中關閉消息隊列客戶端ip
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<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(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<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); } }